﻿/// <reference path="./../../typings/tsd.d.ts" />

interface iCer {
    KeyBitLength: string;
    email: string;
    userID: string;
    creatdate: string;
}
interface IMenuItem {
    LanguageJsonName: string
    showName: string
    icon: string
}

interface emailSupplier{
    name:string;
    title:string;
    imageHtml:string;
    linkButton:string;
    canAccess:KnockoutObservable<boolean>;
    note:Array<string>;
    bkColor:string;
    starNumber:number;
    freeAccount:boolean;
	appHelpLink?: string[];
}
interface StringValidator {
    isAcceptable(s: string): boolean;
}
interface IemailProvider{
    name: string;
    img: string;
    index: number;
    spanClass: string;
}

/**
 * 			getImapSmtpHost
 * 		@param email <string>
 * 		@return Imap & Smtp info
 */
const getImapSmtpHost = ( email: string ) => {
	
	const yahoo = ( domain: string ) => {
		
		if ( /yahoo.co.jp$/.test ( domain ))
			return 'yahoo.co.jp';
			
		if ( /((.*\.){0,1}yahoo|yahoogroups|yahooxtra|yahoogruppi|yahoogrupper)(\..{2,3}){1,2}$/.test ( domain ))
			return 'yahoo.com';
		
		if ( /(^hotmail|^outlook|^live|^msn)(\..{2,3}){1,2}$/.test ( domain ))
			return 'hotmail.com';
			
		if ( /^(me|^icould|^mac)\.com/.test ( domain ))
			return 'me.com'

		return domain
	}
	const emailSplit = email.split ( '@' );
	
	if ( emailSplit.length !== 2 ) 
		return null
		
	const domain = yahoo ( emailSplit [1] )
	
	const ret = {
		imap: 'imap.' + domain,
		smtp: 'smtp.' + domain,
		SmtpPort: [587,465],
		ImapPort: 993,
		imapSsl: true,
		smtpSsl: true,
		haveAppPassword: false,
		ApplicationPasswordInformationUrl: [
			
		]
	}
	
	switch ( domain ) {
		//		yahoo domain have two different 
		//		the yahoo.co.jp is different other yahoo.*
		case 'yahoo.co.jp': {
			ret.imap = 'imap.mail.yahoo.co.jp';
			ret.smtp = 'smtp.mail.yahoo.co.jp'
			ret.SmtpPort = [465]
		}
		break;

		//			gmail
		case 'google.com':
		case 'googlemail.com':
		case 'gmail': {
			ret.haveAppPassword = true;
			ret.ApplicationPasswordInformationUrl = [
				'https://support.google.com/accounts/answer/185833?hl=zh-Hans',
				'https://support.google.com/accounts/answer/185833?hl=ja',
				'https://support.google.com/accounts/answer/185833?hl=en'
			]
		}
		break;
		
		//				yahoo.com
		case 'rocketmail.com':
		case 'y7mail.com':
		case 'ymail.com':
		case 'yahoo.com': {
			ret.imap = 'imap.mail.yahoo.com'
			ret.smtp = (/^bizmail.yahoo.com$/.test(emailSplit[1]))
				? 'smtp.bizmail.yahoo.com'
				: 'smtp.mail.yahoo.com'
			ret.haveAppPassword = true;
			ret.ApplicationPasswordInformationUrl = [
				'https://help.yahoo.com/kb/SLN15241.html',
				'https://help.yahoo.com/kb/SLN15241.html',
				'https://help.yahoo.com/kb/SLN15241.html'
			]
		}
		break;
		
		//		gmx.com
		
		case 'gmx.com' : {
			ret.smtp = 'mail.gmx.com'
		}
		break;
		
		//		aim.com
		case 'aim.com': {
			ret.imap = 'imap.aol.com'
		}
		break;
		
		//	outlook.com
		case 'windowslive.com':
		case 'hotmail.com': 
		case 'outlook.com': {
			ret.imap = 'imap-mail.outlook.com'
			ret.smtp = 'smtp-mail.outlook.com'
		}
		break;
		
		//			apple mail
		case 'me.com': {
			ret.imap = 'imap.mail.me.com'
			ret.smtp = 'smtp.mail.me.com'
			
		}
		break;
		
		//			163.com
		case '126.com':
		case '163.com': {
			ret.imap = 'appleimap.' + domain
			ret.smtp = 'applesmtp.' + domain
			ret.SmtpPort = [465]
		}
		break;
		
		case 'sina.com':
		case 'yeah.net': {
			ret.SmtpPort = [465]
			ret.smtpSsl = false
		}
		break;
		
	}
	
	return ret
	
}

const uuid_generate = () => {
    let lut: Array < string > = [];
    for ( let i = 0; i < 256; i++ ) {
            lut [i] = ( i < 16 ? '0' : '') + ( i ).toString ( 16 );
        }
    let d0 = Math.random () * 0xffffffff | 0;
    let d1 = Math.random () * 0xffffffff | 0;
    let d2 = Math.random () * 0xffffffff | 0;
    let d3 = Math.random () * 0xffffffff | 0;
    return  lut[ d0 & 0xff ]+ lut [d0 >> 8 & 0xff ] + lut [ d0 >> 16 & 0xff ] + lut [ d0 >> 24 & 0xff ] + '-' +
        lut [ d1 & 0xff ]+ lut [ d1 >> 8 & 0xff ] +'-'+ lut [ d1 >> 16 & 0x0f | 0x40 ] + lut[ d1 >> 24& 0xff ] + '-' +
        lut [ d2 & 0x3f | 0x80 ]+ lut [ d2 >> 8 & 0xff ] + '-' + lut [ d2 >> 16 & 0xff]+ lut [ d2 >> 24 & 0xff ] +
        lut [ d3 & 0xff ]+ lut [ d3 >> 8 & 0xff ] + lut [ d3 >> 16 & 0xff] + lut [ d3 >> 24 & 0xff ];
}

const getNickName = ( email: string ) => {
    var ret = '';
    if ( email.length ){
        ret = email.split ('@')[0];
        ret = ret.charAt (0).toUpperCase () + ret.slice(1);
    }
    return ret;
}

/**
 *      check email address
 *      @param email <string>
 *      @param return <string>  Valid = '' Err = errorMessage
 */
const checkEmail = ( email: string ) => {
    
    if ( testVal.isAcceptable ( email )) {
       return 'required'
    } 
    
    if ( ! testEmail.isAcceptable ( email ))
    {
        return 'EmailAddress'
    }
    
    return ''
}

class IsNullValidator implements StringValidator {
    isAcceptable ( s: string ) {
        if ( s === undefined ) {
            return true;
        }
        if ( s === null ) {
            return true;
        }
        if ( s.length == 0 ) {
            return true;
        }
    }
}

class LettersOnlyValidator implements StringValidator {
    isAcceptable ( s: string ) {
        return lettersRegexp.test ( s );
    }
}

class EmailValidator implements StringValidator {
    isAcceptable ( s: string ) {
        return EmailRegexp.test( s );
    }
}

class ZipCodeValidator implements StringValidator {
    isAcceptable ( s: string ) {
        return s.length === 5 && numberRegexp.test (s);
    }
}

class numberValidator implements StringValidator{
    isAcceptable ( s: string ) {
        return numberRegexp.test ( s );
    }
}

const testVal = new IsNullValidator()
const testEmail = new EmailValidator()
const testNumber = new numberValidator()
//********************************************************************************************
/// <reference path="./../../typings/tsd.d.ts" />
const cookieName = 'langEH'

const EmailSuppliers:Array<emailSupplier> =[
    {
        name:'Yahoo',
        bkColor:'op-amber',
        starNumber:5,
        title:'Yahoo mail',
        imageHtml:'/images/Yahoo_Logo.svg',
        linkButton:'http://login.yahoo.com/config/mail',
        canAccess:ko.observable(false),
        freeAccount:true,
		appHelpLink:[
			'https://help.yahoo.com/kb/SLN15241.html'
		],
        note:['雅虎的免费Email服务,每个用户无限Email容量,单个Email附件最大25MB。',
        'Yahooフリーメールサービス、無制限ボックス容量、添付ファイルは25MBまで',
        'Free mail from Yahoo, unlimited inbox, a 25 MB limit on attachments.'
        ]
    },
    {
        name:'gmx',
        bkColor:'op-olive',
        starNumber:4,
        title:'GMX mail',
        imageHtml:'/images/Gmx_email_logo_2.svg',
        linkButton:'http://www.gmx.com/mail',
        canAccess:ko.observable(false),
		appHelpLink:[
			'',
			'',
			''
		],
        freeAccount:true,
        note:['GMX公司提供的免费Email服务, 每个用户2GB Email容量, IMAP单日上下流量不详, 单个Email附件最大50MB。不支持中文。',
        'マイクロソフトフリーメールサービス、2GBボックス容量、IMAP帯域幅制限はわからない、添付ファイルは50MBまで、英語オンリー。',
        'Free mail from GMX, 2GB inbox,  Bandwidth limit is unknow. A 50 MB limit on attachments.'
        ]
    },
    
    {
        name: 'google',
        bkColor: 'op-default',
        starNumber: 5,
        title: 'Google mail',
        imageHtml: '/images/Logo_Google_2013_Official.svg',
        linkButton: 'https://www.gmail.com',
        canAccess: ko.observable(false),
        freeAccount: true,
		appHelpLink: [
			'https://support.google.com/accounts/answer/185833?hl=zh-Hans',
			'https://support.google.com/accounts/answer/185833?hl=ja',
			'https://support.google.com/accounts/answer/185833?hl=en'
		],
        note: ['Google的免费Email服务,每个用户15GBEmail容量, IMAP单日上下流量限制为3GB，单个Email附件最大25MB。',
        'Gmailフリーメールサービス、15GBボックス容量、IMAP帯域幅制限は1日あたり3GBまで、添付ファイルは25MBまで',
        'Free mail from Google, 15GB inbox, Bandwidth limit is 3GB every day.　A 25 MB limit on attachments.'
        ]
    },
    
    {
        name:'Aol',
        bkColor:'op-red',
        starNumber:4,
        title:'Aol mail',
        imageHtml:'/images/AOL_logo.svg',
        linkButton:'https://mail.aol.com',
        canAccess:ko.observable(false),
        freeAccount:true,
        note:['美国在线提供的免费Email服务,每个用户无限Email容量,单个Email附件最大25MB。不支持中文。',
        'AOLフリーメールサービス、無制限ボックス容量、添付ファイルは25MBまで、英語オンリー。',
        'Free mail from Aol,  unlimite inbox, a 25 MB limit on attachments.'
        ]
        
    },
    
    {
        name:'outlook',
        bkColor:'op-indigo',
        starNumber:5,
        title:'Microsoft mail',
        imageHtml:'/images/Outlook.com_logo_and_wordmark.svg',
        linkButton:'https://signup.live.com/signup',
        canAccess:ko.observable(false),
        freeAccount:true,
		appHelpLink:['http://windows.microsoft.com/zh-cn/windows/app-passwords-two-step-verification',
			'http://windows.microsoft.com/ja-jp/windows/app-passwords-two-step-verification',
			'http://windows.microsoft.com/en-us/windows/app-passwords-two-step-verification'],
        note:['微软的免费Email服务,每个用户无限Email容量,单个Email附件最大20MB。中国用户如果使用本系统来翻墙,请注意不要选择居住地为中国来注册账户。',
        'マイクロソフトフリーメールサービス、無制限ボックス容量、添付ファイルは20MBまで、中国に住むユーザは、お住まい国を中国以外を選んでください。',
        'Free mail from Microsoft, unlimited inbox, a 20 MB limit on attachments. Do not choose China when signup at Country/region. '
        ]
    },
    
    {
        name:'iCloud',
        bkColor:'op-orange',
        starNumber:5,
        title:'Apple mail',
        imageHtml:'/images/iCloud.svg',
        linkButton:'https://www.icloud.com/',
        canAccess:ko.observable(false),
        freeAccount:true,
        note:['Apple的免费Email服务,每个用户无限Email容量,单个Email附件最大20MB。中国用户如果使用本系统来翻墙,请注意不要选择居住地为中国来注册账户。',
        'アップルフリーメールサービス、無制限ボックス容量、添付ファイルは20MBまで、中国に住むユーザは、お住まい国を中国以外を選んでください。',
        'Free mail from Apple, unlimited inbox, a 20 MB limit on attachments. Do not choose China when signup at Country/region. '
        ]
    }
    
]
const infoDefine = [
    {
        'components_ProxyViaEmail_addAnEmail': {
            'smtpDomain': '送信服务器域名：',
            'semtpConnect': '尝试连接送信服务器：',
            'smtpAuth':'登陆送信服务器：'
        },
        'errorMessage': {
            'required': '请填写此字段',
            'EmailAddress': '请按以下格式输入你的电子邮件地址: someone@example.com.',
            'SameEmailAddress': '重复的Email地址',
            'smtpServerDomainErrer': 'Email发送服务器域名错误！, 请核对Email地址@字符以后的服务器信息，或手工填入送信服务器网址。',
            'smtpServerConnectError': 'Email发送服务器不能被连接, 大部分情况下是通讯端口号错误, 请填写正确SMTP端口号,或联系Email服务供应商来获得正确的端口号。',
            'smtpAuthError': '登陆Email发送服务器错误，您的用户名和密码有误！',
            'htmlServerError_notSuccess': '和本地服务器通讯错误，请检查网络连接和本地服务器状态',
            'SystemPasswordError': '密码错误，请重试！如果您已忘记您的系统密码，请删除现有的密钥对，重新生成新的密钥对。但您的原有设定将全部丢失！',
            'deleteKeyPairInfo': '注意：删除现有的密钥对您的设定将全部丢失！',
            
            'SystemResetMessage': 'Vpn.Email系统已发送一封系统重置的邮件到您的邮箱，请检查您的邮箱，按邮件里的［重置系统］按钮来重新设置系统。',
            'fileCreateError': '文件创建错误，请检查您的操作系统。',
            'ProxyViaEmailError': '本系统出现未知错误！请重新安装本系统',
            'PasswordlengthError': '必须设定密码为5个字符以上。',
            'SystemPasswordDelete':'密码已删除，请重新设置系统。',
            'portNumberError':'请输入从1到65535之间的数字。',
            'sameEmailAddress':'相同Email重复登记。',
            'titleNotSave':'警  告！',
            'imapPortErr':'指定的端口无法链接Imap服务器，请核对端口号。',
            'haveNotSave':'您还没有保存您的设定，请先保存您的信息。',
            'emailSetupDataFormat':'您的设定有误，请检查您的email设置。',
            'iMapServerAuthenticationFailed':'IMAP用户名或密码错误，请检查。%ImapServiceOpen%',
            'detail':'<a href="%1",target="_blank">详情请点击</a>',
            'iMapServerAuthenticationFailed_IMAPservice':'有可能您的%1邮箱未开启IMAP服务。%2。',
            'iMapServerAuthenticationFailed_AppPassword':'有可能您没有设定%1密码。%2',
            'smtpServerAuthenticationFailed':'SMTP用户名或密码错误，请检查。',
            'cantConnectImapServer':'不能连接IMAP服务器，请检查IMAP服务器名。',
            'needPasswordForContinue':'请输入您的密钥对密码，解锁系统继续完成设定。',
            'smtpPortErr':'指定的端口无法链接Smtp服务器，请核对端口号。',
            'SmtpCertErr':'指定的SMTP服务器提示错误的证书，连接终止！',
            'smtpServerLimit':'邮箱服务器提示您的邮箱今天可发Email数量已用完。',
            'ImapCertErr':'指定的IMAP服务器提示错误的证书，连接终止！',
            'imapServerDomainErr':'Imap服务器不能到达，请检查Imap服务器网址，如果服务器网址设定无误，则该服务器有可能被防火墙屏蔽，请联系您的网络管理员或直接使用IP地址，您也可选择使用其他的Email服务商。',
            'smtpServerDomainErr':'Smtp服务器不能到达，请检查Smtp服务器网址，如果服务器网址设定无误，则该服务器有可能被防火墙屏蔽，请联系您的网络管理员或直接使用IP地址，您也可选择使用其他的Email服务商。'
        },
        "legal": {
            'title': "产品及服务使用协议",
            'item': '欢迎使用Vpn.Email, 感谢您使用我们的产品和服务(下称“服务”)。 服务由 Vpn.Email network technolog Canada Ltd. 下称“Vpn.Email”提供, ' +
            '您使用我们的服务即表示您已同意本条款。 请仔细阅读。',
            'title1': '使用服务',
            'item1': [
                { 'text': '您必须遵守服务中提供的所有政策。' },
                { 'text': '请勿滥用我们的服务, 举例而言: 请勿干扰我们的服务或尝试使用除我们提供的界面和指示以外的方法访问这些服务。您仅能在法律(包括适用的出口和再出口管制法律和法规)允许的范围内使用我们的服务。'+
                    '如果您不同意或遵守我们的条款或政策, 请不要使用我们所提供的服务, 或者我们在调查可疑的不当行为, 我们可以暂停或终止向您提供服务。' },
                { 'text': '连接日志的保管和披露政策: 为了反击滥用及政府反恐需要, 我们始终保留3个月或以上的中继服务器的连接日志,日志内容仅限于: (日期和时间, 目标服务器DNS及IP地址, 链接协议, '+
                    '客户端的email地址和通讯字节数。我们不保存客户端的IP地址。) 除此之外, 没有其他任何信息将被记录在我们的日志服务器上。您使用我们的服务, 就意味着您同意我们可以使用这些信息, ' + 
                    '进行各类统计和分析工作, 以帮助我们改进并提供更好的服务。' },
                { 'text': '我们从不保存每次通讯的具体内容, 所以我们不能回复这样的要求。连接日志的披露以加拿大法律为准。3个月以上的日志有可能已被删除。为了反恐的需要, 我们会向持有加拿大法院令的执法机构提供日志文件。' +
                    '如果您是加拿大以外地区的执法机构,有这方面信息披露的需求, 请联系加拿大外交部, http://www.international.gc.ca/' },
                { 'text': '如果您是被授权的加拿大执法机构, 请通过以下Email联系我们: info@Vpn.Email。' },
            ],
            'title2': '关于我们服务中的软件',
            'item2': [
                { 'text': 'Vpn.Email授予您免许可使用费、不可转让的、非独占的全球性个人许可, 允许您使用由 Vpn.Email 提供的、包含在服务中的软件。' +
                    '本许可仅旨在让您通过本条款允许的方式使用由 Vpn.Email 提供的服务并从中受益。您不得复制、修改、发布、出售或出租我们的服务, 或所含软件的任何部分。' },
            ],
            'title3': '修改和终止服务',
            'item3': [
                { 'text': '我们始终在不断更改和改进我们的服务。我们可能会增加或删除功能, 也可能暂停或彻底停止某项服务。' },
                { 'text': '您可以随时停止使用我们的服务, 尽管我们对此表示非常遗憾, 我们不会退还已付的服务费。Vpn.Email 也可能随时停止向您提供服务, 或随时对我们的服务增加或设置新的限制。' },
            ],
            'title4': '保证和免责声明',
            'item4': [
                { 'text': '我们在提供服务时将会尽到商业上合理水平的技能和注意义务, 希望您会喜欢使用它们。但有些关于服务的事项恕我们无法作出承诺。' },
                { 'text': '某些司法管辖区域会规定特定保证, 例如适销性、特定目的适用性及不侵权的默示保证。在法律允许的范围内, 我们排除所有保证。' },
                { 'text':'在法律允许的范围内, Vpn.Email 不承担利润损失、收入损失或数据、财务损失或间接、特殊、后果性、惩戒性或惩罚性损害赔偿的责任。对于本条款项下任何索赔, ' +
                    '包括任何默示保证的全部赔偿责任限于您因使用服务而向我们支付的金额, 或我们亦可选择, 再次向您提供该服务。在所有情况下, Vpn.Email对于任何不能合理预见的损失或损害不承担责任。'},
            ],
            'title5': '服务的商业使用',
            'item5': [
                { 'text': '如果您代表某家企业使用我们的服务, 该企业必须接受本条款。对于因使用本服务或违反本条款而导致的或与之相关的任何索赔、起诉或诉讼, 包括因索赔、损失、损害赔偿、起诉、判决、' +
                    '诉讼费和律师费而产生的任何责任或费用, 该企业应对 Vpn.Email 及其关联机构、管理人员、代理机构和员工进行赔偿并使之免受损害。' },
            ],
            'title6': '关于本协议',
            'item6': [
                { 'text': '我们可以修改上述条款或任何适用于某项服务的附加条款, 例如为反映法律的变更或我们服务的变化而进行的修改。您应当定期查阅本协议。我们会在网页上公布这些条款的修改通知。' +
                    '我们会在适用的服务中公布附加条款的修改通知。所有修改的适用不具有追溯力, 修改将立即生效。如果您不同意服务的修改条款, 应立即停止使用本服务。' },
                {'text': '本条款约束 Vpn.Email 与您之间的关系, 且不创设任何第三方受益权。如果您不遵守本条款, 且我们未立即采取行动, 并不意味我们放弃我们可能享有的任何权利, ' +
                    '例如在将来采取行动。如果某一条款不能被强制执行, 这不会影响其他条款的效力。' },
                { 'text': '请通过以下Email联系我们: info@Vpn.Email。' }
            ],
        },
        "info": {
            "finished": "完成",
            "failed":"故障"
        },
        "btn": {
            "next": "下一步",
            'allow':'同意协议并继续',
            "home": "返回系统主页",
            "eMailServiceList": "推荐的Email服务商列表",
            "ok": '提交',
            'checking': '验证中...',
            'portName': '通讯端口号：',
            'AutoSetup': '自动设定' ,
            'customSetup': '手动设定',
            'join':'加入',
            'CANTreach':'不能到达',
            'cancel':'放弃操作',
            'creatKeyPair':'创建密钥对...',
            'delete':'删除',
            'delete_check':'确认删除',
            'signUpTitle':'加 入',
            'serverdetail':'手动输入详细设定：',
            'otherSelect':'其他Port:',
            'unlockKeyPair':'密钥对解锁',
            'deleteKeyPair':'删除密钥对',
            'Ssl':'使用加密信息传输：',
            'logout':'退出登录',
            'checkout':'信用卡或支付宝支付',
            'stopCreateKeyPair': '停止生成密钥对',
            'continueCreateKeyPair': '继续生成',

        },
        'input': {
            'emailAddress': 'Email地址(必填)',
            'systemPassword':'系统密码',
            'password': '密码',
            'smtpServer': "SMTP送信服务器设定",
            "imapServer": 'IMAP服务器设定',
            'smtpServerInput': '送信服务器(smtp)网址',
            'imapServerinput': '收件服务器(IMAP)网址',
            'UserName': '用户名',
            "ServerUserSelect":"使用上述Email和密码作为登陆凭据",
            "SystemAdministratorNickName":"昵称或组织名(必填)",
            'portNumber':'端口号'
        },
        "problem_view": {
            "info_problem": "糟糕，看起来系统出了点小问题，让我们一起来试着解决它吧！"
        },
        "home_index_view": {
            "welcome": '从此您将可以勇敢地开始您的冒险！',
            "info": 'Vpn.Email是一个安全通讯手段，利用VPN和Email协议相结合，最大限度的保护您的网络通讯不被检测和干扰，建立一个私密的网络安全通道。',
            'title1': 'Vpn.Email的特点: ',
            'node1': '使用加密Email作为载体, 由中继服务器替代您访问您所需的网络资源。',
            'title2':'Vpn.Email要解决的问题:',
            'node2': '1. 匿名上网: 当您访问网络时, 您的IP地址即被记录在被访问的服务器上, 而IP地址通常是可以被用来跟踪您的个人信息。所以大家都选择VPN服务来保护自己。而您不要忘了，你其实把全部秘密告诉了VPN服务商，只是瞒着被你访问的网站而已。' +
                '如果您遇到一个蜜罐，你对他们就没有秘密可言。他们可以集中掌握你的一切，包括你当前在哪里，都去访问了些什么。而Vpn.Email因为使用Email的IMAP通讯协议，所以Vpn.Email不需要您的IP地址，就可以为您服务。',
            'node2_1': '2. 穿越防火墙: 某些防火墙限制了您访问网络的自由。您只要可以收发Email，就可以使用我们的服务，即便您处在防火墙内。',
            'node2_2': '3. 抗干扰, 高可靠性。因为传统的VPN和Tor等技术都首先由客户端向VPN主机发出链接请求，服务商必须提供主机的IP地址给客户端，而且在通讯的过程中通讯指纹明显，很容易被'+
                '具有学习功能的现代防火墙所区别，从而进行干扰和截断，所以VPN用户会感觉速度不稳定，主机链接不上等通讯故障。而服务商也需要不断变化主机IP来适应防火墙的屏蔽，'+
                'Vpn.Email技术是让服务器主动链接到您的EMail邮箱，您只需连接到您的Email邮箱即可开启一条VPN通讯管道，而防火墙技术目前还不能区分正常Email通讯和VPN的Email之间有何区别。',
            'node2_3': '4. 安全网络通讯: 由于使用加密OpenGPG技术, 使您的访问内容不易被监听及泄露。',
            'node2_4': '5. 高速通讯: Vpn.Email由于采用最新的NodeJS技术，程序轻量且高速。',
            'node2_5': '6. 定制代码优化的Lunix代理服务器，流量要求高的商用客户可选用Vpn.Email提供的独立服务器，独占GB带宽。',
            'title3': 'Vpn.Email的优点:',
            'node3': '1. 由于可并联多条IMAP线路同时通讯, 通讯速度快, 高稳定性和可靠性, 能安装在目前的任何计算机平台, 而且安装简单, 使用方便。' +
                '目前终端软件对应Mac OSX, Windows, Linux, SunOS等平台, 今后会陆续推出手机应用和方便携带的无线路由设备。',
            'node3_1': '2. 主机会24小时不间断的链接着您的EMail邮箱，随时随刻服务于您（限付费用户）。', 
            'node3_2': '3. 相比传统的VPN链接, 本系统减少了信息泄漏的风险。 因为当您使用传统的VPN时, 您必须提供您所目前使用的IP地址, 这样您对VPN服务商而言, '+
                '您并不是匿名的。Vpn.Email由于使用IMAP通讯, 所以中继服务器不需要您现在的IP地址, 而且Vpn.Email也没有有效的技术来获得您目前位置。',
            'node3_3': '4. 本系统的中继服务器分布在世界各地, 您可以挑选您喜爱的地方的中继服务器, 来访问您的目标主机。',
            'node3_4': '5. 本系统设定完成后, 您的其他设备包括手机，可以通过VPN拨号或Proxy代理设定，来共享本系统, 甚至您出门在外都可以通过家里的本系统访问网络。',
            'title4': 'Vpn.Email的劣势:',
            'node4': '受Email服务商的服务制约, 如IMAP同时连接数限制和每天IMAP通讯数据限制。Email服务提供商会保存IAMP连接日志,和您的邮件(当然，Email服务提供商没法阅读Vpn.Email通讯时加密的Email)的风险。',
            "stat": "系统概括:",
            "item": "项目",
            "subStat": "状态",
            "item1": "系统初始化",
            "item2": "互联网",
            "item3": "代理服务器设定帮助",
            "item4": "已连接代理服务器设备数",
            "item5": "Vpn.Email网关状态"
        },
        "config_index_view": {
            "title": "系统设置",
            "item1": "初始化设定文件",
        },
        "error_404_view": {
            "title":"出错啦!无此服务"
        },
        "password_view": {
			'appPasswordInfo':'如果你已启用双重验证，并在Vpn.Email看到了密码不正确的错误，则你需要获取并输入一个唯一的应用密码，以进行登录。 使用应用密码进行登录后，你便可以照常使用该应用或设备。 对于每个无法提示你输入安全代码的应用或设备，你都需要创建一个新的应用密码并使用该密码进行登录。',
			'appInfoTitle':'关于APP密码',
            'info1': '让我们来完成最后几步的设定吧',
            'inputEmail': '<span>首先完成系统加密用密匙生成, 这个Email地址, 应使用您的常用Email地址, 它将被用作您的Vpn.Email账号。</span><h6 class="fg-red">由于Vpn.Email在某些国家和地区被防火墙屏蔽而不能正常收发Vpn.Email的Email，如果您不幸是处于防火墙内的用户，建议使用自由世界的邮件服务商如雅虎邮箱或Outlook，苹果公司的邮箱作为注册用户。</h6>',
            'inputEmailTitle': '通讯专用Email邮箱',
			'activeViewTitle': '验证您的注册邮箱',
            'info2': '请输入系统用来通讯的Email邮箱。这个邮箱是Vpn.Email和您通讯时使用的，它会产生大量通讯信息，并且这个邮箱的设定信息会提交Vpn.Email。' +
                '为了防止您的个人信息被泄漏，这里请不要使用您的常用邮箱。请在Outlook或Yahoo等免费邮箱供应商，申请一个新的邮箱。',
            'info2_1':'<p><dt>警告：</dt></p>当您按下提交按钮时，意味着您已经确认：这个邮箱并不是您常用的邮箱，这是为了使用Vpn.Email系统而特别申请的临时邮箱，您同意承担由此带来的风险，并授权Vpn.Email系统可以使用这个Email邮箱传送信息!',
			'info5':'您的邮箱还未完成验证，Vpn.Email已向您的注册邮箱［',
			'info6':']发送了一封加密邮件，请检查您的邮箱。如果存在多封从Vpn.Email过来的邮件时，以最后一封为准，打开信件并复制邮件内容从“-----BEGIN PGP MESSAGE----- （开始，一直到）-----END PGP MESSAGE-----” 结束的完整内容，粘贴到下面的输入框中。',
			'info3': 'Vpn.Email推荐的免费邮箱供应商',
            'info9':'您的email地址还未获得Vpn.Email的验证。',
            'info10':'您的email地址已验证。',
			'info4':'关于APP密码',
            'info8':'正在验证收到的邮件。',
            'info7':'<p class="fg-red">格式错误：正确的示例如下：</p><span class="fg-cyan"><p>-----BEGIN PGP MESSAGE-----</p><p>Version: GnuPG v1</p><p></p><p>xsBNBFcOxUgBB/9Vx9vpSKrrBq0C6aJDZAXqiTMEbaPAdwd+yjQCKb8aCZVl</p><p>Xe0CdSEPedDOuGcNKv3cCZ+1WsprEgGPWg5Yvqge1eMIiD0rmkjNLWDFXrxq</p><p>zeUiYfsuq66WIje4DNwUjgiuG6Kf1RgB3+e9VlUb2FfmkYIfnm6ol4R1XeZk</p></span><span class="fg-red"><p>.</p><p>［示例省略了若干行］</p><p>.</p></span><span class="fg-cyan"><p>jy4y56RrIhimCZNh2Y/4mmp8FzVwBBg95wWwICoqfphvbb4PUZh4pCu6REPI</p><p>4YZYheb2RIo1z+/bzg==</p><p>=ogvx</p><p>-----END PGP MESSAGE-----</p></span>',
			'placeholder1':'请粘贴从“-----BEGIN PGP MESSAGE----- ・・・・・・・  -----END PGP MESSAGE-----” 结束的完整内容',
            'selectService': '从推荐的服务商中新建Email',
            'SystemPasswordTitle': '请设置管理员密码',
            'systemPasswordInfo': '这个密码用来加密您的系统设置, 必须4个以上字符, 请妥善保管!',
            'eMailFormInfo': '系统用来传送网络信息的Email, 您可以添加任意多个Email, 供本系统使用, 来加快网络传送速度。',
            'newEmailAccount':'请申请一个专用Email来使用本系统。如果您需要用本系统来翻墙，则建议使用防火墙外Email。',
            'systemAlreadyInit':'密 钥',
            'deleteSystemPasswordWarning':'按「下一步」您将删除整个系统设定！',
            'systemAdministratorEmail':'系统管理员信息输入',
            'AdministratorEmailTitle':'请输入您常用的Email地址，这个地址是注册Vpn.Email用户和系统重置时使用的。',
            'GenerateKeypair':'<em>系统正在生成用于通讯和签名的RSA加密密钥对，计算机需要运行产生大量的随机数字有，可能需要几分钟时间，尤其是长度为4096的密钥对，需要特别长的时间，请耐心等待。关于RSA加密算法的机制和原理，您可以访问维基百科：' +
                '<a href="https://zh.wikipedia.org/wiki/RSA加密演算法" target="_blank ">https://zh.wikipedia.org/wiki/RSA加密演算法</a></em>',
            'passwordStrength':'密码强度 : ',
            'passwordStrengthWeek':'弱',
            'passwordStrengthGood':'好',
            'passwordStrengthStrong':'强',
            'passwordStrengthVeryStrong':'超强',
            'KeypairLength':'请选择加密通讯用密钥对长度：这个数字越大，越难被破解，但会增加通讯量和运算时间。',
            'creatDate':'加密密钥创建日期：',
            'keyLength':'密钥强度：',
            'keyPairNickName':'创建人称谓：',
            'emailAccountpassword':'邮箱密码，注意：Gmail或hotmail要输入应用程序密码。',
            'accountRegistration':'注册Vpn.Email账户',
            'accountRegistrationInformation':'请选择注册Vpn.Email账户类型。',
            'accountTypeTitle':'请选择注册账户类型',
            'mouthly':'每月支付us$',
            'saveMoney':'节省：us$',
            'free':'免费',
            'yearly':'支付一年us$',
            'discount':'折扣',
            'mouth':'月',
            'year':'年',
            'everyDayTransfer':'24小时内最大通讯量:',
            'noMaxTransferEachDay':'无限制',
            'overBandWidthPrice':'月度通讯量超过部分每GB收取us$',
            'paymentByCard':'信用卡支付',
            'cardNumber':'信用卡卡号',
            'cardNumberLabel':'请输入您的信用卡号码',
            'cardNumberERROR':'非常抱歉，目前暂不接受此类信用卡',
            'cardDateInput':'有效期限格式:月/年',
            'cardDateERROR':'此卡已过有効期限！',
            'cardNumberCvcError': '信用卡安全码长度应该是3位或4位数字',
            'cardNumberCvc': '信用卡背面的签名栏处的CVC安全码3或4位数字',
            'cardNumberCvcHold': '安全码CVC',
            'cardNumberFormatError': '信用卡号码位数有误。',
            'cardNameHold': '持卡人名称',
            'cardNameLable': '请按照信用卡上英文字母顺序键入。',
            'cardPostCode': '邮政编码',
            'cardAddress': '持卡人地址',
            'cardTelphone': '持卡人电话号码'
            
        }

    }, {
        'components_ProxyViaEmail_addAnEmail': {
            'smtpDomain': 'SMTPドメイン名：',
            'semtpConnect': 'SMTPサーバーへ接続:',
            'smtpAuth': 'SMTPサーバーへ登録：'
        },
        'errorMessage': {
            'required': 'このフィールドを入力してください。',
             'EmailAddress': 'メール アドレスを someone@example.com の形式で入力してください。',
            'SameEmailAddress': '重複しているメールアドレス',
            'smtpServerDomainErrer': '送信ホストが見つかりません!Emailアドレスのサーバー名を確認してください、または送信ホスト名を入れてください。',
            'smtpServerConnectError': '送信ホストへ接続ができません。多分ポート番号が間違っています、Emailプロバイダーへ連絡して正しいポート番号を入れてください。',
            'smtpAuthError':'送信ホストへ登録ができません、Emailアドレス又はパースワードが間違っています！',
            'htmlServerError_notSuccess':'ローカルサーバーへの通信は故障があります、ネットワークまたはローカルサーバーをチェックしてください。',
            'SystemPasswordError':'パスワードが違います。パースワードが忘れた場合、現在の鍵ペアを削除してください。この場合は、現有の設定は全部なくなって、一からシステム設定をやり直しが必要です。',
            'deleteKeyPairInfo': '鍵ペアを削除することで、現有の設定は全部なくなって、一からシステム設定をやり直しが必要です。',
            'SystemResetMessage':'システムリセットメールを送りました。メールをチェックして、メールにある「リセット」ボタンを押してください。',
            'fileCreateError':'新規ファイルができません、OSをチェックしてください。',
            'ProxyViaEmailError':'本システムはハンドルできないエラーが発生しました、大変申し訳ないですが一から再インストールしてください。',
            'PasswordlengthError':'5文字以上の長さのパスワードが必要。',
            'SystemPasswordDelete':'パースワード削除しました。システムを再設置をしてください。',
            'portNumberError':'ポード番号は1から65535までの範囲でです',
            'sameEmailAddress':'同じEmail重複入力',
            'titleNotSave':'警　告',
            'smtpServerLimit':'EMAILプロバイダーは今日の発信数が1日に送信可能な数（閾値）を超えて、送信制限になっている模様です。',
            'certErr':'接続先のサーバは提示した証書が問題がありました。接続中止をします。',
            'imapPortErr':'指定したポートに、Imap接続ができません。ポート番号を確認してからもう一回実行をください。',
            'smtpPortErr':'指定したポートに、Smtp接続ができません。ポート番号を確認してからもう一回実行をください。',
            'haveNotSave':'未保存している設定データがございますが、セーブをしてください。',
            'emailSetupDataFormat':'間違いEMAIL設置がありますからチェックをしてください。',
            'iMapServerAuthenticationFailed':'IMAP登録名またはパースワードに間違いがあります。登録ができません！',
            'smtpServerAuthenticationFailed':'SMTP登録名またはパースワードに間違いがあります。登録ができません！',
            'cantConnectImapServer':'IMAPサーバーへ接続ができません。IMAPサーバー名間違ったかをチェックをください。',
            'needPasswordForContinue':'暗号鍵ペアがロックしていましが、鍵ペアパースワードを入力して、設定をし続きてください。',
            'imapServerDomainErr':'Imapサーバのドメイン名が見つかりません。もしドメイン名が正いければ、ファイアウォールなどでブロックされているかもしれません。ネットワーク管理者に連絡し、又はダイレクトIPアドレスを使うか、その他のEmailサービスを変更してください。',
            'smtpServerDomainErr':'Smtpサーバのドメイン名が見つかりません。もしドメイン名が正いければ、ファイアウォールなどでブロックされているかもしれません。ネットワーク管理者に連絡し、又はダイレクトIPアドレスを使うか、その他のEmailサービスを変更してください。'
        },
        "legal": {
            'title': "产品使用协议",
            'item': '欢迎使用Vpn.Email,感谢您使用我们的产品和服务(下称“服务”)。服务由 Coco network technolog Canada Ltd.下称“Coco CA”提供' +
            '您使用我们的服务即表示您已同意本条款。请仔细阅读。',
            'title1': '使用服务',
            'item1': [
                { 'text': 'J您必须遵守服务中提供的所有政策。' },
                { 'text': 'J请勿滥用我们的服务。' },
                { 'text': 'J' }]
        },
        "info": {
            "finished": "完了",
            "failed": "故障"
        },
        "btn": {
            "next": "次へ",
            'allow': '協議を合意し、次へ',
            "home": "システムホームに戻る",
            "eMailServiceList": "お勧め無料Emailサービスリスト",
            "ok": '送信',
            'checking': '検証中...',
            'portName': 'ポート：',
            'AutoSetup': '自動設定',
            'customSetup':'カスタム',
            'join':'加わる',
            'CANTreach':'到達できない',
            'cancel':'操作停止',
            'creatKeyPair':'暗号鍵ペアを生成...',
            'delete':'削除',
            'delete_check':'削除確認',
            'signUpTitle':'選択する',
            'serverdetail':'詳細設定:',
            'otherSelect':'その他ポート番号:',
            'unlockKeyPair':'暗号鍵ペアをアンロック',
            'deleteKeyPair':'暗号鍵ペアを削除',
            'logout':'ログアウト',
            'Ssl':'暗号化通信：',
            'checkout':'カード及びアリペイで決済',
            'stopCreateKeyPair': '暗号鍵ペア生成をキャンセル',
            'continueCreateKeyPair': '生成を続きします',
        },
        'input': {
            'emailAddress': 'Emailアドレス(必須)',
            'systemPassword':'システムパスワード',
            'password': 'パスワード',
            'smtpServer': "smtp設定",
            "imapServer": 'IMAP設定',
            'smtpServerInput': 'smtpサーバー名',
            'imapServerinput': 'IMAPサーバー名',
            'UserName': 'ユーザー名',
            "ServerUserSelect": "",
            "SystemAdministratorNickName":'ニックネーム(必須)',
            'portNumber':'ポート番号'
        },
        "problem_view": {
            "info_problem": "ちょっと待ってください！トラブル発生、チェックをしましょう！"
        },
        "home_index_view": {
            "welcome": 'これから、勇気づけられたネットワークのエクスプレス旅にしましょう。',
            "info": 'Vpn.Emailはカナダ Vpn.Email network security 株式会社運営する実験的なシステムです。目的としてはインターネットの通信自由とセキュリティのために、技術的な道を探しているものであります。',
            'title1':'Vpn.Emailの特徴。',
            "stat": "システム概要:",
            "item": "アイテム",
            "subStat": "ステータス",
            "item1": "システム初始化",
            "item2": "インターネット",
            "item3": "プロキシサーバ情報",
            "item4": "クライアント接続数",
            "item5": "Vpn.Emailゲートウェイ状態",
        },
        "config_index_view": {
            "title": "システム設置",
            "item1": "パラメータファイルの初期化",
        },
        "error_404_view": {
            "title": "ご請求されたページは無いです"
        },
        "password_view": {
			'appInfoTitle':'APPパースワードについて',
            'info1': 'さって、最後の設定を完成させよう。',
            'info2': 'Vpn.Email通信専用emailを入力。そのemailアカウント情報はVpn.Emailへ提供して、ローカルネットワークとVpn.Emailお互い通信します。' +
				'個人情報漏洩の恐れとそのemailアカウントに大量なダミ情報を生成するので、OutlookやYahooなどフリーメールに、新たなemailアカウントをつくてください。',
            'info2_1':'<p><dt>以下の事項を確認してから送信ボタンを押してください：</dt></p>このEmailアカンウトはあなたのよく使っているEmailアカンウトと違って、Vpn.Emailシステムを使用するのために、'+
                '一時的新たに作ったEmailアカンウトです。あなたはVpn.EmailにこのEmailアカンウトを使用して、ネットワーク通信することを了承しました。',
			'info3': 'Vpn.Emailおすすめのフリーメール',
			'info4':'APPパースワードについて',
            'info8':'メールを検証中。',
			'info5':'emailアドレスを検証は未完成です。Vpn.Emailは宛先「',
            'info11':'emailアドレスを検証中',
			'info6':'」に検証メールをしました。メールボックスをチェックして、Vpn.Emailから多数メールの場合は、最後のを選んでください。その検証メールの内容「-----BEGIN PGP MESSAGE-----」から「-----END PGP MESSAGE-----」'+
				'までの全てをコピーして、以下の入力フィルターにペーストをしてください。',
			'info7':'<p class="fg-red">フォーマットエラー、以下のは正しい表示例です：</p><span class="fg-cyan"><p>-----BEGIN PGP MESSAGE-----</p><p>Version: GnuPG v1</p><p>xsBNBFcOxUgBB/9Vx9vpSKrrBq0C6aJDZAXqiTMEbaPAdwd+yjQCKb8aCZVl</p><p>Xe0CdSEPedDOuGcNKv3cCZ+1WsprEgGPWg5Yvqge1eMIiD0rmkjNLWDFXrxq</p><p>zeUiYfsuq66WIje4DNwUjgiuG6Kf1RgB3+e9VlUb2FfmkYIfnm6ol4R1XeZk</p></span><span class="fg-red"><p>.</p><p>［n行列略］</p><p>.</p></span><span class="fg-cyan"><p>jy4y56RrIhimCZNh2Y/4mmp8FzVwBBg95wWwICoqfphvbb4PUZh4pCu6REPI</p><p>4YZYheb2RIo1z+/bzg==</p><p>=ogvx</p><p>-----END PGP MESSAGE-----</p></span>',
            'info9':'そのemailアドレスはまだ検証されていません。',
            'info10':'アドレスは検証しました。',
            'placeholder1':'メールの内容「-----BEGIN PGP MESSAGE-----  ・・・・・・・  -----END PGP MESSAGE-----」までの全て、ペーストをしてください。 ',
			'appPasswordInfo':'2段階認証を有効にしていて、Vpn.Emailで無効なパスワードのエラーが表示される場合は、一意のアプリパスワードを取得し、それを入力してサインインする必要があります。',
            'inputEmail': '<span>管理員Emailの入力。このEmailはVpn.Emailへユーザ登録やシステムリセットなどの時使います。</span><h6 class="fg-red">Vpn.Emailドメイン名は、ファイヤウォールがある国または地域にブラックリストに入って行って、Vpn.Emailシステムへ登録完了することができませんので、ユーザの通信自由な地域にあるEmailプロバイダを利用することがお勧めです。</h6>',
            'inputEmailTitle': '通信専用Emailアカーンドを登録',
			'activeViewTitle':'管理員Email検証',
            'selectService': 'お勧めリストから新規Email',
            'SystemPasswordTitle': 'システム管理者パースワードを設置',
            'systemPasswordInfo': 'このシステムセキュリティ用パースワード、大切にしてください。',
            'newEmailAccount':'以下のメールサービスからこのシステム専用メールを新規してください。特にこのシステムを使ってファイヤウォールを通す場合なら、ファイヤウォールの外側のメールシステムを使った方がおすすめです。',
            'systemAlreadyInit':'鍵ペア',
            'deleteSystemPasswordWarning':'警告！「次へ」するとシステムの設定が無くなります。',
            'systemAdministratorEmail':'システム管理者インフォーメーション',
            'AdministratorEmailTitle':'よく使うEmailを入力してください。Vpn.Emailへユーザ登録やシステムリセットする際このメールアドレスを使います。',
            'GenerateKeypair':'<em>強秘匿性通信するのために、RSA暗号鍵ペアを生成中、大量なランダム数字が発生し、数分かかる場合もあります、4096ビットの場合、特に時間がかかります、しばらくお待ち下さい。RSA暗号技術について、ウィキペディア百科辞典を参考してください：' +
                '<a href="https://ja.wikipedia.org/wiki/RSA暗号" target="_blank">https://ja.wikipedia.org/wiki/RSA暗号</a></em>',
            'passwordStrength':'パスワード強度 : ',
            'passwordStrengthWeek':'弱',
            'passwordStrengthGood':'良い',
            'passwordStrengthStrong':'強い',
            'passwordStrengthVeryStrong':'超強い',
            'KeypairLength':'RSA暗号鍵ペアの長度を選んでください。この数字が長ければ、長いほど秘匿性によいですが、スピードが遅くなります。',
            'creatDate':'暗号鍵ペア生成日：',
            'keyLength':'強度の長さ：',
            'keyPairNickName':' ニックネーム：',
            'emailAccountpassword':'メールアカーンドパスワード。GmailやHotmailなどを使う時、2段階認証プロセスをして、アプリパスワードを入力してください。',
            'accountRegistration':'Vpn.Emailアカーンド',
            'accountRegistrationInformation':'Vpn.Emailへようこそ！',
            'keyPairPassword':'鍵ペアパスワード:',
            'accountTypeTitle':'アカンウトを選択',
            'mouth':'月',
            'saveMoney':'割引：us$',
            'year':'年',
            'free':'フリー',
            'mouthly':'毎月のお支払いus$',
            'yearly':'年払いus$',
            'everyDayTransfer':'24時間内通信量制限:',
            'noMaxTransferEachDay':'無制限',
            'overBandWidthPrice':'月通信量制限を超えた分GB毎にus$',
            'paymentByCard':'クレジットカードで決済',
            'cardNumber':'クレジットカード番号',
            'cardNumberFormatError':'クレジットカード番号桁数が足りないです。',
            'cardNumberLabel':'あなたのクレジットカード番号入力をください',
            'cardNumberERROR':'ごめんなさい、暫くこの種類のカードでのご決済ができません。',
            'cardDateInput':'有効期限フォーマットは:月/年です',
            'cardDateERROR':'このカードは有効期限切れです',
            'cardNumberCvc':'カードの裏面にある3又は4桁のセキュリティコード',
            'cardNumberCvcError': 'クレジットカードのセキュリティコードは3又は4桁です。',
            'cardNumberCvcHold':'セキュリティコードCVC',
            'cardNameHold': 'カード名義人の名前',
            'cardNameLable': 'カードに載せている順番で入力してください。',
            'cardPostCode': 'カード名義人の郵便番号',
            'cardAddress': 'カード名義人の住所',
            'cardTelphone': 'カード名義人の電話番号'
            
        }
    }, {
        'components_ProxyViaEmail_addAnEmail': {
            'smtpDomain': 'SMTP server name:',
            'semtpConnect': 'Try connect to server:',
            'smtpAuth': 'Login to Smtp server：'
        },
        'errorMessage': {
            'required': 'Please fill in this field.',
            'EmailAddress': 'Please enter your email address in the format someone@example.com.',
            'SameEmailAddress': 'Duplicate email address!',
            'smtpServerDomainErrer': 'Smtp server name mistake! Please check the part of after @. Or enter the SMTP server name and try again.',
            'smtpServerConnectError': "Can't connect to SMTP server, Please check the port number, ",
            'smtpAuthError':'SMTP server login error, Please check your Email address and password.',
            'htmlServerError_notSuccess':"Can't connect to local server, please check your network or local server status.",
            'SystemPasswordError':'Your password did not match. Please try again. If you forgot your password, pless delete this key pair. That will let you lost all setup.',
            'deleteKeyPairInfo': 'Note: Delete key pair will lost all your system setup.',
            'SystemResetMessage':'A email sent to your mail address. Please click [Reset] to reset System.',
            'fileCreateError':"Can't create file! Please check your OS.",
            'ProxyViaEmailError':'Vpn.Email had unhandle error, please re-install Vpn.Email.',
            'PasswordlengthError':'Passwords must have at least 5 characters.',
            'SystemPasswordDelete':'System password has been delete. Please return to setup.',
            'portNumberError':'Port number is from 1 to 65535.',
            'sameEmailAddress':'Same email address duplicate.',
            'titleNotSave':'Warning!',
            'smtpServerLimit':'Oppps! The email provate looks outbound email was limited.',
            'certErr':"Server's certificate error, connect stoped.",
            'haveNotSave':'Looks your setup data have not save to server yet, Please save its before liver the page.',
            'emailSetupDataFormat':'Please check your email setup.',
            'smtpPortErr':"The Smtp port can't connect. Please verify that and try it again.",
            'imapPortErr':"The imap port can't connect. Please verify that and try it again.",
            'iMapServerAuthenticationFailed':'IMAP user name or password was incorrect, please check its.',
            'smtpServerAuthenticationFailed':'SMTP user name or password was incorrect, please check its.',
            'cantConnectImapServer':"Ooops! cann't connect to IMAP server. Please check your IMAP name.",
            'needPasswordForContinue':'Please unlock the key pair, continue system setup.',
            'imapServerDomainErr':'Imap domain cannot be contacted. If that domain name is correct, maybe blocked by firewall. Please contact your network administrator, or use direct IP address, or change to other email privade.',
            'smtpServerDomainErr':'Smtp domain cannot be contacted. If that domain name is correct, maybe blocked by firewall. Please contact your network administrator, or use direct IP address, or change to other email privade.'
        },
        "legal": {
            'title': "产品使用协议",
            'item': '欢迎使用Vpn.Email,感谢您使用我们的产品和服务(下称“服务”)。服务由 Coco network technolog Canada Ltd.下称“Coco CA”提供' +
            '您使用我们的服务即表示您已同意本条款。请仔细阅读。',
            'title1': '使用服务',
            'item1': [
                { 'text': 'E您必须遵守服务中提供的所有政策。' },
                { 'text': 'E请勿滥用我们的服务。' },
                { 'text': 'E' }]
        },
        "info": {
            "finished": "Completed",
            "failed": "failed"

        },
        "btn": {
            "next": "Next",
            'allow': 'I AGREE',
            "home": "return to home",
            "eMailServiceList": "Free Email service list",
            "ok": 'Submit',
            'checking': 'Checking...',
            'portName': 'Port：',
            'AutoSetup': 'Auto',
            'customSetup': 'Custom setup',
            'join':'join',
            'CANTreach':"Can't reach",
            'cancel':'Cancel',
            'creatKeyPair':'Generate key pair...',
            'delete':'Delete',
            'delete_check':'Yes, delete it',
            'signUpTitle':'Chooese',
            'serverdetail':"Settings.",
            'otherSelect':'Other port:',
            'unlockKeyPair':'Unlock key Pair',
            'deleteKeyPair':'Delete key pair.',
            'Ssl':'secure: ',
            'logout':'Logout',
            'checkout':'Pay with Card or Alipay',
            'stopCreateKeyPair': 'Cancel generate key pair',
            'continueCreateKeyPair': 'Keep generate',
        },
        'input': {
            'emailAddress': 'Email Address (Required)',
            'systemPassword':'System Password',
            'password': 'Password',
            'smtpServer': "SMTP setup",
            "imapServer": 'IMAP setup',
            'smtpServerInput': 'SMTP server name',
            'imapServerinput': 'IMAP server name',
            'UserName': 'user name',
            'SystemAdministratorNickName':'Nick name (Required)',
            'portNumber':'Port number'
        },
        "problem_view": {
            "info_problem": "Oops! System looks have some problems, let us clear that!",
        },
        "home_index_view": {
            "welcome": 'Welcome to Vpn.Email',
            "info": 'Vpn.Email实验项目是一个在线服务,由加拿大Vpn 公司为学术研究目的运营。' +
            '本研究的目的是保护个人隐私,维护网络自由。',
            'title1': 'Vpn.Email的特点',
            "stat": "Summary:",
            "item": "Items",
            "subStat": "status",
            "item1": "System initialization process",
            "item2": "Internet access",
            "item3": "Proxy Server information",
            "item4": "connected clients",
            "item5": "Vpn.Email gateway status",
        },
        "config_index_view": {
            "title": "System Setup",
            "item1": "Setup initialization file",

        },
        "error_404_view": {
            "title": "Error, page not found!"
        },
        "password_view": {
			'appPasswordInfo': "If you've turned on two-step verification and you see an incorrect password error with Vpn.Email, you'll need to get and enter a unique app password to sign in. Once you've signed in with your app password, you're all set to use that app or device. You'll need to create and sign in with a new app password for each app or device that can't prompt you for a security code.",
			'appInfoTitle': 'About APP password',
            'info1': 'Let us finishe setup.',
            'info2_1':'<p><dt>By clicking submit you are agreeing to this:</dt></p>This is a temporary email account for use Vpn.Email system. ' +
                'You agree Vpn.Email can use this email account for transfer data. ',
            'info2':"This email account will use for communicate between Vpn.Email and your local network." +
                "For your personal information privacy, please register a new account at Yahoo or Gmail.",
			'info3': 'The best email services.',
			'info4':'About APP password.',
            'info8':'Validating...',
            'info9':'This email address have not be validated with Vpn.Email',
            'info10':'This email address has been verified.' ,
			'info5':'Verify email have not complete. A verification email from Vpn.Email sent to your [',
			'info6':'] email box. Please check your mailbox. If one more mail from Vpn.Email in your mailbox, Please open the latest one. Copy all content from [-----BEGIN PGP MESSAGE-----] ... to [-----END PGP MESSAGE-----]. Paste into the text box.',
            'info7':'<p class="fg-red">Format mistake：The correct is:</p><span class="fg-cyan"><p>-----BEGIN PGP MESSAGE-----</p><p>Version: GnuPG v1</p><p>xsBNBFcOxUgBB/9Vx9vpSKrrBq0C6aJDZAXqiTMEbaPAdwd+yjQCKb8aCZVl</p><p>Xe0CdSEPedDOuGcNKv3cCZ+1WsprEgGPWg5Yvqge1eMIiD0rmkjNLWDFXrxq</p><p>zeUiYfsuq66WIje4DNwUjgiuG6Kf1RgB3+e9VlUb2FfmkYIfnm6ol4R1XeZk</p></span><span class="fg-red"><p>.</p><p>[omission]</p><p>.</p></span><span class="fg-cyan"><p>jy4y56RrIhimCZNh2Y/4mmp8FzVwBBg95wWwICoqfphvbb4PUZh4pCu6REPI</p><p>4YZYheb2RIo1z+/bzg==</p><p>=ogvx</p><p>-----END PGP MESSAGE-----</p></span>',
            'placeholder1':'please paste all content from -----BEGIN PGP MESSAGE----- ... to -----END PGP MESSAGE-----',
			'inputEmail': `<span>The Email address will use to regiest a Vpn.Email user account.</span><h6 class="fg-red">Because Vpn.Email looks in firewall's black list at some area. The best way is chooess your Yahoo mail or Outlook, iCloud email address. </h6>`,
            'inputEmailTitle': 'Transfer email account.',
			'activeViewTitle':'Verify your email address',
            'selectService': 'Sinup via email service list',
            'SystemPasswordTitle': 'Please setup the root password',
            'systemPasswordInfo': 'This is system security protocol password. Please take care it',
            'newEmailAccount':'Chooses an email provide to regulation a new email address for use our system. Note: You should be use a email provide that in outside firewall when you use our service to over firewall.',
            'systemAlreadyInit':'Key pair',
            'deleteSystemPasswordWarning':'WARNING!. YOU WILL LOST ALL SETUP WHEN PLESS NEXT.',
            'systemAdministratorEmail':'Administrator information.',
            'AdministratorEmailTitle':'Use your favorite email address, for create a account of Vpn.Email and when you want reset system.',
            'GenerateKeypair':'<em>Generate RSA Key pair. It may take a few minutes. It will need more long time when you chooess 4096 bit key length. About RSA keypair system can be found here: ' +
                '<a href="http://en.wikipedia.org/wiki/RSA_(cryptosystem)" target="_blank">http://en.wikipedia.org/wiki/RSA_(cryptosystem)</a></em>',
            'passwordStrength':'Password strength : ',
            'passwordStrengthWeek':'Week.',
            'passwordStrengthGood':'Good.',
            'passwordStrengthStrong':'Strong.',
            'passwordStrengthVeryStrong':'Very strong.',
            'KeypairLength':'Please select the bit length of your key pair. longest will hard be broken, also hard for network transfer speeds.',
            'creatDate':'Created date: ',
            'keyLength':'Key pair length: ',
            'keyPairNickName':'Nick name: ',
            'emailAccountpassword':"Enter email account's password. Should be application password when your account as Gmail or Hotmail.",
            'accountRegistration':'Vpn.Email Account',
            'accountRegistrationInformation':'Welcome to Vpn.Email. ',
            'accountTypeTitle':'Account Type',
            'mouth': 'Month',
            'year': 'Year',
            'saveMoney': 'save：',
            'free': 'Free',
            'mouthly': 'Mouthly pay us$',
            'yearly': 'Yearly pay us$',
            'everyDayTransfer': 'Max bandwidth in 24 hours:',
            'noMaxTransferEachDay': 'No limit',
            'overBandWidthPrice': 'Over bandwidth each MB price us$',
            'paymentByCard': 'Pay by credit card.',
            'cardNumber': 'Credit card number',
            'cardNumberLabel': 'Your credit number',
            'cardNumberERROR': 'Sorry. We do not accept this kind credit card payments yet.',
            'cardDateInput': 'Valid thru fromat is: MM/YY',
            'cardDateERROR': 'The card has expired!',
            'cardNumberCvc': 'The CVV/CVC number in the signature area of the back of your card.',
            'cardNumberCvcError': 'The CVV/CVC number must be 3 or 4 digits code.',
            'cardNumberCvcHold': 'CVV/CVC number',
            'cardNumberFormatError': 'credit card numbers must be 15 digits or 16 digits code.',
            'cardNameHold': 'Card holder name',
            'cardNameLable': 'Card holder name',
            'cardPostCode': 'Post code',
            'cardAddress': 'Address',
            'cardTelphone': 'Telphone number'
        }

    },{
        'components_ProxyViaEmail_addAnEmail': {
            'smtpDomain': '送信服務器域名：',
            'semtpConnect': '嘗試連接送信服務器：',
            'smtpAuth':'登入送信服務器：'
        },
        'errorMessage': {
            'required': '請填寫此字段',
            'EmailAddress': '請按照下列格式輸入你的電子郵件地址: someone@example.com.',
            'SameEmailAddress': '重複的Email地址',
            'smtpServerDomainErrer': 'Email發送服務器域名錯誤！ , 請核對Email地址@字符以後的服務器信息，或手工填入送信服務器網址。',
            'smtpServerConnectError': 'Email發送服務器不能被連接, 大部分情況下是通訊端口號錯誤, 請填寫正確SMTP端口號​​,或聯繫Email服務供應商來獲得正確的端口號。',
            'smtpAuthError': '登入Gmail發送服務器錯誤,您的用戶名和密碼有誤!',
            'htmlServerError_notSuccess': '和本地服務器通訊錯誤，請檢查網絡連接和本地服務器狀態',
            'SystemPasswordError': '密碼錯誤，請重試！如果您已忘記您的系統密碼，請刪除現有的密鑰對，重新生成新的密鑰對。但您的原有設定將全部丟失！',
            'deleteKeyPairInfo': '注意：删除现有的密钥对您的设定将全部丢失！',
            'SystemResetMessage': 'Vpn.Email系統已發送一封系統重置的郵件到您的郵箱，請檢查您的郵箱，按郵件裡的［重置系統］按鈕來重新設置系統。',
            'fileCreateError': '文件創建錯誤，請檢查您的操作系統。',
            'ProxyViaEmailError': '本系統出現未知錯誤！請重新安裝本系統。',
            'PasswordlengthError': '密碼必須設定為5個字符以上。',
            'SystemPasswordDelete':'密碼已刪除，請重新設置系統。',
            'portNumberError':'請輸入從1到65535之間的數字。',
            'sameEmailAddress':'相同Email重複登記。',
            'titleNotSave':'警 告！',
            'imapPortErr':'指定的端口无法连接Imap服务器,请審核端口号。',
            'haveNotSave':'您還沒有保存您的設定，請先保存您的信息。',
            'emailSetupDataFormat':'您的設定有誤，請檢查您的email設置。',
            'iMapServerAuthenticationFailed':'IMAP用戶名或密碼錯誤，請檢查。%ImapServiceOpen%',
            'detail':'<a href="%1",target="_blank">詳情請點擊</a>',
            'iMapServerAuthenticationFailed_IMAPservice':'有可能您的%1郵箱未開啟IMAP服務。%2。',
            'iMapServerAuthenticationFailed_AppPassword':'有可能您沒有設定%1密碼。%2',
            'smtpServerAuthenticationFailed':'SMTP用戶名或密碼錯誤，請檢查。',
            'cantConnectImapServer':'不能連接IMAP服務器，請檢查IMAP服務器名。',
            'needPasswordForContinue':'請輸入您的密鑰對密碼，解鎖系統繼續完成設定。',
            'smtpPortErr':'在指定的端口無法連接Smtp服務器,請核對端口號。',
            'SmtpCertErr':'指定的SMTP服務器提示錯誤的證書，連接終止！',
            'smtpServerLimit':'郵箱服務器提示您的郵箱今天可發Email數量已用完。',
            'ImapCertErr':'指定的IMAP服務器提示錯誤的證書，連接終止！',
            'imapServerDomainErr':'Imap服務器不能到達，請檢查Imap服務器網址，如果服務器網址設定無誤，則該服務器有可能被防火牆屏蔽，請聯繫您的網絡管理員或直接使用IP地址，您也可選擇使用其他的Email服務商。',
            'smtpServerDomainErr':'Smtp服務器不能到達，請檢查Smtp服務器網址，如果服務器網址設定無誤，則該服務器有可能被防火牆屏蔽，請聯繫您的網絡管理員或直接使用IP地址，您也可選擇使用其他的Email服務商。'
        },
        "legal": {
            'title': "產品及服務使用協議",
            'item': '歡迎使用Vpn.Email, 感謝您使用我們的產品和服務(下稱“服務”)。服務由 Vpn.Email network technolog Canada Ltd. 簡称“Vpn.Email”提供, ' +
            '您使用我們的服務即表示您已同意本條款。請仔細閱讀。',
            'title1': '使用服務',
            'item1': [
                { 'text': '您必須遵守服務中提供的所有政策。' },
                { 'text': '請勿濫用我們的服務, 舉例而言: 請勿干擾我們的服務或嘗試使用除我們提供的界面和指示以外的方法訪問這些服務。您僅能在法律(包括適用的出口和再出口管制法律和法規)允許的範圍內使用我們的服務。'+
                    '如果您不同意或遵守我們的條款或政策, 請不要使用我們所提供的服務, 或者我們在調查可疑的不當行為, 我們可以暫停或終止向您提供服務。' },
                { 'text': '連接日誌的保管和披露政策: 為了反擊濫用及政府反恐需要, 我們始終保留3個月或以上的中繼服務器的連接日誌,日誌內容僅限於: (日期和時間, 目標服務器DNS及IP地址, 鏈接協議, '+
                    '客戶端的email地址和通訊字節數。我們不保存客戶端的IP地址。 ) 除此之外, 沒有其他任何信息將被記錄在我們的日誌服務器上。您使用我們的服務, 就意味著您同意我們可以使用這些信息, ' + 
                    '進行各類統計和分析工作, 以幫助我們改進並提供更好的服務。' },
                { 'text': '我們從不保存每次通訊的具體內容, 所以我們不能回复這樣的要求。連接日誌的披露以加拿大法律為準。 3個月以上的日誌有可能已被刪除。為了反恐的需要, 我們會向持有加拿大法院令的執法機構提供日誌文件。' +
                    '如果您是加拿大以外地區的執法機構,有這方面信息披露的需求, 請聯繫加拿大外交部, http://www.international.gc.ca/' },
                { 'text': '如果您是被授權的加拿大執法機構, 請通過以下Email聯繫我們: info@Vpn.Email。' },
            ],
            'title2': '關於我們服務中的軟件',
            'item2': [
                { 'text': 'Vpn.Email授予您免許可使用費、不可轉讓的、非獨占的全球性個人許可, 允許您使用由 Vpn.Email 提供的、包含在服務中的軟件。' +
                    '本許可僅旨在讓您通過本條款允許的方式使用由 Vpn.Email 提供的服務並從中受益。您不得複制、修改、發布、出售或出租我們的服務, 或所含軟件的任何部分。' },
            ],
            'title3': '修改和終止服務',
            'item3': [
                { 'text': '我們始終在不斷更改和改進我們的服務。我們可能會增加或刪除功能, 也可能暫停或徹底停止某項服務。' },
                { 'text': '您可以隨時停止使用我們的服務, 儘管我們對此表示非常遺憾, 我們不會退還已付的服務費。 Vpn.Email 也可能隨時停止向您提供服務, 或隨時對我們的服務增加或設置新的限制。' },
            ],
            'title4': '保證和免責聲明',
            'item4': [
                { 'text': '我們在提供服務時將會盡到商業上合理水平的技能和注意義務, 希望您會喜歡使用它們。但有些關於服務的事項恕我們無法作出承諾。' },
                { 'text': '某些司法管轄區域會規定特定保證, 例如適銷性、特定目的適用性及不侵權的默示保證。在法律允許的範圍內, 我們排除所有保證。' },
                { 'text':'在法律允許的範圍內, Vpn.Email 不承擔利潤損失、收入損失或數據、財務損失或間接、特殊、後果性、懲戒性或懲罰性損害賠償的責任。對於本條款項下任何索賠,' +
                    '包括任何默示保證的全部賠償責任限於您因使用服務而向我們支付的金額, 或我們亦可選擇, 再次向您提供該服務。在所有情況下, Vpn.Email對於任何不能合理預見的損失或損害不承擔責任。'},
            ],
            'title5': '服務的商業使用',
            'item5': [
                { 'text': '如果您代表某家企業使用我們的服務, 該企業必須接受本條款。對於因使用本服務或違反本條款而導致的或與之相關的任何索賠、起訴或訴訟, 包括因索賠、損失、損害賠償、起訴、判決、' +
                    '訴訟費和律師費而產生的任何責任或費用, 該企業應對 Vpn.Email 及其關聯機構、管理人員、代理機構和員工進行賠償並使之免受損害。' },
            ],
            'title6': '關於本協議',
            'item6': [
                { 'text': '我們可以修改上述條款或任何適用於某項服務的附加條款, 例如為反映法律的變更或我們服務的變化而進行的修改。您應當定期查閱本協議。我們會在網頁上公佈這些條款的修改通知。' +
                    '我們會在適用的服務中公佈附加條款的修改通知。所有修改的適用不具有追溯力, 修改將立即生效。如果您不同意服務的修改條款, 應立即停止使用本服務。' },
                {'text': '本條款約束 Vpn.Email 與您之間的關係, 且不創設任何第三方受益權。如果您不遵守本條款, 且我們未立即採取行動, 並不意味我們放棄我們可能享有的任何權利,' +
                    '例如在將來採取行動。如果某一條款不能被強制執行, 這不會影響其他條款的效力。' },
                { 'text': '請通過以下Email聯繫我們: info@Vpn.Email。' }
            ],
        },
        "info": {
            "finished": "完成",
            "failed":"故障"
        },
        "btn": {
            "next": "下一步",
            'allow':'同意協議並繼續',
            "home": "返回系統主頁",
            "eMailServiceList": "推薦的Email服務商列表",
            "ok": '提交',
            'checking': '驗證中...',
            'portName': '通訊端口號：',
            'AutoSetup': '自動設定' ,
            'customSetup': '手動設定',
            'join':'加入',
            'CANTreach':'不能到達',
            'cancel':'放棄操作',
            'creatKeyPair':'創建密鑰對..',
            'delete':'刪除',
            'delete_check':'確認刪除',
            'signUpTitle':'加 入',
            'serverdetail':'手動輸入詳細設定：',
            'otherSelect':'其他Port:',
            'unlockKeyPair':'密鑰對解鎖',
            'deleteKeyPair':'刪除密鑰對',
            'Ssl':'使用加密信息傳輸：',
            'logout':'退出登入',
            'checkout':'信用卡或支付寶支付',
            'stopCreateKeyPair': '停止生成密鑰對',
            'continueCreateKeyPair': '繼續生成',

        },
        'input': {
            'emailAddress': 'Email地址(必填)',
            'systemPassword':'系統密碼',
            'password': '密碼',
            'smtpServer': "SMTP送信服務器設定",
            "imapServer": 'IMAP服務器設定',
            'smtpServerInput': '送信服務器(smtp)網址',
            'imapServerinput': '收件服務器(IMAP)網址',
            'UserName': '用戶名',
            "ServerUserSelect":"使用上述Email和密碼作為登錄憑據",
            "SystemAdministratorNickName":"暱稱或組織名(必填)",
            'portNumber':'端口號'
        },
        "problem_view": {
            "info_problem": "糟糕，看起來系統出了點小問題，讓我們一起來試著解決它吧！"
        },
        "home_index_view": {
            "welcome": '从此您将可以勇敢地开始您的冒险！',
            "info": 'Vpn.Email是一個安全通訊手段，利用VPN和Email協議相結合，最大限度的保護您的網絡通訊不被檢測和乾擾，建立一個私密的網絡安全通道。',
            'title1': 'Vpn.Email的特點: ',
            'node1': '使用加密Email作為載體, 由中繼服務器替代您訪問您所需的網絡資源。',
            'title2':'Vpn.Email要解決的問題:',
            'node2': '1. 匿名上網: 當您訪問網絡時, 您的IP地址即被記錄在被訪問的服務器上, 而IP地址通常是可以被用來跟踪您的個人信息。所以大家都選擇VPN服務來保護自己。而您不要忘了，你其實把全部秘密告訴了VPN服務商，只是瞞著被你訪問的網站而已。' +
                '如果您遇到一個蜜罐，你對他們就沒有秘密可言。他們可以集中掌握你的一切，包括你當前在哪裡，都去訪問了些什麼。而Vpn.Email因為使用Email的IMAP通訊協議，所以Vpn.Email不需要您的IP地址，就可以為您服務。',
            'node2_1': '2. 穿越防火牆: 某些防火牆限制了您訪問網絡的自由。您只要可以收發Email，就可以使用我們的服務，即便您處在防火牆內。',
            'node2_2': '3. 抗干擾, 提高通訊可靠性。因為傳統的VPN和Tor等技術都首先由客戶端向VPN主機發出鏈接請求，服務商必須提供主機的IP地址給客戶端，而且在通訊的過程中通訊指紋明顯，很容易被'+
                '具有學習功能的現代防火牆所區別，從而進行干擾和截斷，所以VPN用戶會感覺速度不穩定，主機鏈接不上等通訊故障。而服務商也需要不斷變化主機IP來適應防火牆的屏蔽，'+
                'Vpn.Email技術是讓服務器主動鏈接到您的EMail郵箱，您只需連接到您的Email郵箱即可開啟一條VPN通訊管道，而防火牆技術目前還不能區分正常Email通訊和VPN的Email之間有何區別。',
            'node2_3': '4. 安全網絡通訊: 由於使用加密OpenGPG技術, 使您的訪問內容不易被監聽及洩露。',
            'node2_4': '5. 高速通訊: Vpn.Email由於採用最新的NodeJS技術，程序輕量且高速。',
            'node2_5': '6. 定制代碼優化的Lunix代理服務器，流量要求高的商用客戶可選用Vpn.Email提供的獨立服務器，獨占GB帶寬。',
            'title3': 'Vpn.Email的優點:',
            'node3': '1. 由於可並聯多條IMAP線路同時通訊, 通訊速度快, 高穩定性和可靠性, 能安裝在目前的任何計算機平台, 而且安裝簡單, 使用方便。' +
                '目前終端軟件對應Mac OSX, Windows, Linux, SunOS等平台, 今後會陸續推出手機應用和方便攜帶的無線路由設備。',
            'node3_1': '2. 主機會24小時不間斷的鏈接到您的EMail郵箱,隨時隨刻服務於您(限付費用戶)。', 
            'node3_2': '3. 相比傳統的VPN鏈接, 本系統減少了信息洩漏的風險。因為當您使用傳統的VPN時, 您必須提供您所目前使用的IP地址, 這樣您對VPN服務商而言, '+
                '您並不是匿名的。 Vpn.Email由於使用IMAP通訊, 所以中繼服務器不需要您現在的IP地址, 而且Vpn.Email也沒有有效的技術來獲得您目前位置。',
            'node3_3': '4. 本系統的中繼服務器分佈在世界各地, 您可以挑選您喜愛的地方的中繼服務器, 來訪問您的目標主機。',
            'node3_4': '5. 本系統設定完成後, 您的其他設備包括手機，可以通過VPN撥號或Proxy代理設定，來共享本系統, 甚至您出門在外都可以通過家裡的本系統訪問網絡。',
            'title4': 'Vpn.Email的劣勢:',
            'node4': '受Email服務商的服務制約, 如IMAP同時連接數限制和每天IMAP通訊數據限制。 Email服務提供商會保存IAMP連接日誌,和您的郵件(當然，Email服務提供商沒法閱讀Vpn.Email通訊時加密的Email)的風險。',
            "stat": "系統概括:",
            "item": "項目",
            "subStat": "狀態",
            "item1": "系統初始化",
            "item2": "互聯網",
            "item3": "代理服務器設定幫助",
            "item4": "已連接代理服務器設備數",
            "item5": "Vpn.Email網關狀態"
        },
        "config_index_view": {
            "title": "系統設置",
            "item1": "初始化設定文件",
        },
        "error_404_view": {
            "title":"出錯啦!無此服務"
        },
        "password_view": {
			'appPasswordInfo':'如果你已啟用雙重驗證，並在Vpn.Email看到了密碼不正確的錯誤，則你需要獲取並輸入一個唯一的應用密碼，以進行登錄。使用應用密碼進行登錄後，你便可以照常使用該應用或設備。對於每個無法提示你輸入安全代碼的應用或設備，你都需要創建一個新的應用密碼並使用該密碼進行登錄。',
			'appInfoTitle':'關於APP密碼',
            'info1': '讓我們來完成最後的設定吧',
            'inputEmail': '<span>首先完成系統加密用密匙生成, 這個Email地址, 應使用您的常用Email地址, 它將被用作您的Vpn.Email賬號</span><h6 class="fg-red">由於Vpn.Email域名在某些國家和地區被防火牆屏蔽而不能正常收發Vpn.Email的Email，如果您不幸是處於防火牆內的用戶，建議使用自由世界的郵件服務商如雅虎郵箱或Outlook，蘋果公司的郵箱作為註冊用戶。</h6>',
            'inputEmailTitle': '通訊專用Email郵箱',
			'activeViewTitle': '驗證您的註冊郵箱',
            'info2': '請輸入系統用來通訊的Email郵箱。這個郵箱是Vpn.Email和您通訊時使用的，它會產生大量通訊信息，並且這個郵箱的設定信息會提交Vpn.Email。' +
                '為了防止您的個人信息被洩漏，這裡請不要使用您的常用郵箱。請在Outlook或Yahoo等免費郵箱供應商，申請一個新的郵箱。',
            'info2_1':'<p><dt>警告：</dt></p>當您按下提交按鈕時，意味著您已經確認：這個郵箱並不是您常用的郵箱，這是為了使用Vpn.Email系統而特別申請的臨時郵箱，您同意承擔由此帶來的風險，並授權Vpn.Email系統可以使用這個Email郵箱傳送信息!',
			'info5':'您的郵箱還未完成驗證，Vpn.Email已向您的註冊郵箱［',
			'info6':']發送了一封加密郵件，請檢查您的郵箱。如果存在多封從Vpn.Email過來的郵件時，以最後一封為準，打開信件並複制郵件內容從“-----BEGIN PGP MESSAGE----- （開始，一直到）-----END PGP MESSAGE-----” 結束的完整內容，粘貼到下面的輸入框中。',
			'info3': 'Vpn.Email推薦的免費郵箱供應商',
            'info9':'您的email地址還未獲得Vpn.Email的驗證。',
            'info10':'您的email地址已驗證。',
			'info4':'關於APP密碼',
            'info8':'正在驗證收到的郵件。',
            'info7':'<p class="fg-red">格式錯誤：正確的示例如下：</p><span class="fg-cyan"><p>-----BEGIN PGP MESSAGE-----</p><p>Version: GnuPG v1</p><p></p><p>xsBNBFcOxUgBB/9Vx9vpSKrrBq0C6aJDZAXqiTMEbaPAdwd+yjQCKb8aCZVl</p><p>Xe0CdSEPedDOuGcNKv3cCZ+1WsprEgGPWg5Yvqge1eMIiD0rmkjNLWDFXrxq</p><p>zeUiYfsuq66WIje4DNwUjgiuG6Kf1RgB3+e9VlUb2FfmkYIfnm6ol4R1XeZk</p></span><span class="fg-red"><p>.</p><p>［示例省略了若干行］</p><p>.</p></span><span class="fg-cyan"><p>jy4y56RrIhimCZNh2Y/4mmp8FzVwBBg95wWwICoqfphvbb4PUZh4pCu6REPI</p><p>4YZYheb2RIo1z+/bzg==</p><p>=ogvx</p><p>-----END PGP MESSAGE-----</p></span>',
			'placeholder1':'請粘貼從“-----BEGIN PGP MESSAGE----- ・・・・・・・  -----END PGP MESSAGE-----” 結束的完整內容',
            'selectService': '從推薦的服務商中新建Email',
            'SystemPasswordTitle': '請設置管理員密碼',
            'systemPasswordInfo': '這個密碼用來加密您的系統設置, 必須4個以上字符, 請妥善保管!',
            'eMailFormInfo': '系統用來傳送網絡信息的Email, 您可以添加任意多個Email, 供本系統使用, 來加快網絡傳送速度。',
            'newEmailAccount':'請申請一個專用Email來使用本系統。如果您需要用本系統來翻牆，則建議使用防火牆外Email。',
            'systemAlreadyInit':'密 鑰',
            'deleteSystemPasswordWarning':'按「下一步」您將刪除整個系統設定！',
            'systemAdministratorEmail':'系統管理員信息輸入',
            'AdministratorEmailTitle':'請輸入您常用的Email地址，這個地址是註冊Vpn.Email用戶和系統重置時使用的。',
            'GenerateKeypair':'<em>系統正在生成用於通訊和簽名的RSA加密密鑰對，計算機需要運行產生大量的隨機數字有，可能需要幾分鐘時間，尤其是長度為4096的密鑰對，需要特別長的時間，請耐心等待。關於RSA加密算法的機制和原理，您可以訪問維基百科：' +
                '<a href="https://zh.wikipedia.org/wiki/RSA加密演算法" target="_blank ">https://zh.wikipedia.org/wiki/RSA加密演算法</a></em>',
            'passwordStrength':'密碼強度 :',
            'passwordStrengthWeek':'弱',
            'passwordStrengthGood':'好',
            'passwordStrengthStrong':'強',
            'passwordStrengthVeryStrong':'超強',
            'KeypairLength':'請選擇加密通訊用密鑰對長度：這個數字越大，越難被破解，但會增加通訊量和運算時間。',
            'creatDate':'加密密鑰創建日期：',
            'keyLength':'密鑰強度：',
            'keyPairNickName':'創建人稱謂：',
            'emailAccountpassword':'郵箱密碼，注意：Gmail或Hotmail要輸入應用程序密碼。',
            'accountRegistration':'註冊Vpn.Email賬戶',
            'accountRegistrationInformation':'請選擇註冊Vpn.Email賬戶類型。',
            'accountTypeTitle':'請選擇註冊賬戶類型',
            'mouthly':'每月支付us$',
            'saveMoney':'節省：us$',
            'free':'免費',
            'yearly':'支付一年us$',
            'discount':'折扣',
            'mouth':'月',
            'year':'年',
            'everyDayTransfer':'24小時內最大通訊量:',
            'noMaxTransferEachDay':'無限制',
            'overBandWidthPrice':'月度通訊量超過部分每GB收取us$',
            'paymentByCard':'信用卡支付',
            'cardNumber':'信用卡號碼',
            'cardNumberLabel':'請輸入您的信用卡號碼',
            'cardNumberERROR':'非常抱歉，目前暫不接受此類信用卡',
            'cardDateInput':'有效期限格式:月/年',
            'cardDateERROR':'此卡已过有効期限！',
            'cardNumberCvcError': '信用卡安全碼長度應該是3位或4位數字',
            'cardNumberCvc':'信用卡背面的簽名欄處的CVC安全碼3或4位數字',
            'cardNumberCvcHold':'安全碼CVC',
            'cardNumberFormatError':'信用卡號碼位數有誤。',
            'cardNameHold': '持卡人名稱',
            'cardNameLable': '請按照信用卡上英文字母順序鍵入。',
            'cardPostCode': '郵政編碼',
            'cardAddress': '持卡人地址',
            'cardTelphone': '持卡人電話號碼'
        }

    }
]

const changeNotifyLanguage = () => {
    const self = this;
    const obj = $('.notify')
    obj.each ( ( index, element ) => {
        const ele = $(element).find('.notify-text>span.ErrDetail');
        const data = ele.attr('ve-data-bind')
        if (data) {
            const text = eval (data)
            ele.html (text)
        }
        
    })
}

const systemInfomation = [{
    warning:"警　告!",
    no_login:'请登陆后操作！',
    info:"信息",
    UnknowErr: '未知错误，请再试: ',
    UnAllowAccess: '不被许可的访问！',
    offline:'无网络可用，您的计算机似乎未连接到因特网。',
    vpnEmailConnect: 'Vpn.Email服务器联机中！',
    vpnEmailDisconnect: '未连接 Vpn.Email服务器。',
	ECONNREFUSED: '指定端口连接被重置错误。有可能您所在网络不支持或服务器不能在这个端口进行数据通讯，请另换端口试试。',
    vpnviaEmailSystemError: 'Vpn.Email系统错误，重启Vpn.Email后请再试。如连续发生，请重装Vpn.Email系统。',
	'vpnvia.email-timeout': 'Vpn.Email服务器应答超时。有可能您所使用的Email服务商无法发送邮件到Vpn.Email域名，请尝试使用其他Email。或Vpn.Email服务器忙碌，请再试。',
    hostCertError: 'IP证书错误，您有可能正在连接到一个假冒的服务器上，无法继续。如果连续发生，请尝试使用其他Email服务商',
    hostPortTimeOut: '指定端口连接超时，请检查是否端口号是否正确',
    hostAuthTimeOut: '服务器登陆超时，请再试',
    cantDecryption: '提供的验证邮件不能被解密，或不能被验证，请检查您的邮箱，如果有多封从Vpn.Email过来的邮件，请提供最后一封的内容。或删除您的密钥后，重新再试一次。',
    passwordErrMsg: '用户名或密码有误! 请检查您的Email帐号是否[<a target="_blank" href="https://kf.qq.com/faq/120322fu63YV130422mIrYnu.html">启用IMAP</a>]。如果您的Email帐号设定了应用密码和双重验证，你必须在密码栏填入' +
		'［<a target="_blank" href="http://windows.microsoft.com/zh-cn/windows/app-passwords-two-step-verification">应用专用密码</a>］',
    imapEnable: '您的Email账号好像没有启用IMAP访问功能，请进入Email服务商网站，选择[<a target="_blank" href="https://kf.qq.com/faq/120322fu63YV130422mIrYnu.html">启用IMAP</a>]访问',
    hostAddrErr: '服务器IP不能获得，请检查服务器名称是否有误',
    networkOff: "客户端从Internet断开",
    networkOnLine: '客户端连接着Internet',
    networkBack: "网络故障排除",
    permitted: '错误：文件被锁定，不能被操作！',
    anotherLogin: '错误：Vpn.Email已运行中，请输入密码后才能删除。',
    fileCreateError: '文件创建错误，请检查您的服务器操作系统。可能的原因是系统已无空间，或您没有创建文件的权利。',
    newPemDown: '密钥对创建完成！',
    DeletePemOK: '系统密钥对已删除。',
    SendEmailForDeletePem:'系统已发送一封系统重置的邮件到您的邮箱，请检查您的邮箱，按邮件里的［重置系统］按钮来重新设置系统。',
    dataFormatError:'传送到服务器的数据错误，您的操作不能完成！',
    htmlServerError_notSuccess:'本地服务器通讯错误,请检查您的网络或重启本地服务器！',
    keyPairPasswordErr:'密钥对密码错误',
    anotherAccess: 'Vpn.Email检测到有他人试图登陆登陆系统。如果是您了解的，请忽视！',
    multiLogin: 'Vpn.Email设定页面已经在其他浏览器打开！',
    have_keypair: '错误：系统已生成密钥对，如需重新生成，请首先删除原有的密钥对！'
    
},{
    warning:"警　告!",
    no_login:'ログインをしてから操作をしてください。',
    offline:'ネットワークがオフラインになっています。',
    UnAllowAccess:'このアクセスはできない。',
    vpnEmailConnect: 'Vpn.Emailサーバに接続しています。',
    vpnEmailDisconnect: 'Vpn.Emailサーバとの接続は切断されました。',
    'vpnvia.email-timeout':'Vpn.Emailサーバタイムアウトエラー！このIMAPメールはVpn.Emailサーバに送信ができないかもしれないでうsが、他のメールサービスを使ってください。もしくはVpn.Emailサーバが混んでおります、もう一回してください。',
    networkOnLine:'端末はインターネットに接続をしています。',
    cantDecryption:'提供した検証メール暗号文を、復元することができません、又は検証不能になっています。Vpn.Emailから多数のメールがある場合には、最後のメールを選んでください。又は現有暗号鍵ペアを削除して見てください。',
	ECONNREFUSED:　'指定したポートにサーバとのセション接続が拒否されました。サーバにのポート通信が故障にあるか、今いるネットワーク環境にこのポート通信がサポットしないでしょうか。別のポート番号をチェッジして見てください。',
    UnknowErr:'unknowエラーが発生しました、もう1回実行をしてください: ',
    vpnviaEmailSystemError:'Vpn.Emailシステムエラーが発生しました、Vpn.Emailを再起動をしてもう一回試してください。直らない場合はVpn.Emailを再インストールをください。',
    hostCertError:'が不正なセキュリティ証明書を持っています、接続の安全性を確認できません。ほかのメールサービスに変更してください。',
    hostPortTimeOut:'指定するサーバポートへアクセスタイムアウトが発生しました、そのポート番号が間違っているかどうかチェックをしてください',
    hostAuthTimeOut:'サーバへ登録際にタイムアウトが発生しました、もう1回実行をしてください',
    passwordErrMsg: 'ユーザー名またはパスワードが間違っています。「<a target="_blank" href="http://hamachan.info/win7/Outlook/gmail.html">IMAP</a>」に有効していますか'+
		'又は[<a target="_blank" href="http://windows.microsoft.com/ja-jp/windows/app-passwords-two-step-verification">アプリパスワード</a>]をしていますかをチェックしてください。',
    imapEnable: 'IMAPが無効になっているらしい。メールサーブスプロバイダへアカンド設定に、「<a target="_blank" href="http://hamachan.info/win7/Outlook/gmail.html">IMAP</a>」を有効にしてください',
    hostAddrErr: '名からIPアドレスを見つからなかった、サーバ名をチェックしてください',
    anotherLogin:'Vpn.Email運行中、パースワードを入力してから続行してください。',
    permitted:'ファイルはロックされており、操作することができません。',
    info:"インフォーメーション",
    networkOff:"端末はインターネット接続障害中！",
    networkBack:"サーバーネットワーク故障排除しました。",
    fileCreateError:'新規ファイルができません。ハードディスクが一杯になっているか、ファイルをアクセス権がないかをチェックしてください。',
    newPemDown:'暗号鍵ペア作成完了しました。',
    DeletePemOK:'暗号鍵ペア削除しました。',
    SendEmailForDeletePem:'システムリセットメールを送りました。メールをチェックして、メールにある「リセット」ボタンを押してください。',
    dataFormatError:'間違いデータがあります、操作を中止します。',
    htmlServerError_notSuccess:'ローカルサーバーとの通信はミスがありますから、ネットワーク故障あるか、またはサーバーを再起動してください。',
    keyPairPasswordErr:'暗号鍵パスワードが間違っています。',
    anotherAccess:'Vpn.Emailはその他からシステムにアクセスすることが検出しました。ご了解した場合は無視をください。',
    multiLogin: 'Vpn.Emailコントロールは他のブラウザですでにオープンしています。',
    have_keypair: '暗号鍵ペアがすでに存在しています、暗号鍵ペアを削除してから新しいのを作ってください。'
},{
    warning:"Warning!",
    no_login:'Please first do login.',
    offline:'Have no internet. Loos offline.',
    vpnEmailConnect: 'Vpn.Email server connected.',
    vpnEmailDisconnect: ' disconnected from Vpn.Email server.',
    permitted:'Files looks be locked, process canceled',
    'vpnvia.email-timeout':"Vpn.Email server response timeout error. Maybe Vpn.Email address is in provider's black list, please choose other email provider. Or Vpn.Emial server had busy, please try again. ",
    networkOnLine:'Network online.',
    UnAllowAccess:'Un allow access.',
    anotherLogin:'Vpn.Email are running. Please after login than do delete.',
	ECONNREFUSED: 'Network Error: Connection Refused. Please change the port number and try again.',
    cantDecryption:'The content can not be decrypt, or your content can not be Please check your email inbox, make sure it is the lasest mail form Vpn.Email.',
    vpnviaEmailSystemError:'Vpn.Email system had problem. Please restart Vpn.Email and try again. Please re-install system if it still happen.',
    UnknowErr:'Unknow error. Please try again: ',
    hostCertError:"IP doesn't match certificate's altnames. Please try other mail provide.",
    hostPortTimeOut:' port timeout, please check the port number and try again.',
    hostAuthTimeOut:' timed out while authenticating with server, try again.',
    passwordErrMsg: 'User name or password is incorrect. Check the <a target="_blank" href="http://www.howtogeek.com/174837/how-to-add-your-gmail-account-to-outlook-2013-using-imap/">IMAP enable.</a>' +
		'Or <a target="_blank" href="http://windows.microsoft.com/en-us/windows/app-passwords-two-step-verification"> App passwords setup.</a>',
    imapEnable: 'IMAP desable Error, Please check your email account <a target="_blank" href="http://www.howtogeek.com/174837/how-to-add-your-gmail-account-to-outlook-2013-using-imap/">IMAP setup</a>',
    hostAddrErr: " can't get host ip address.",
    info: "Notify",
    networkOff:"Network offline.",
    networkBack:'Server network online now.',
    fileCreateError:"Can't create file! Maybe the hard disk is nearly full or access is denied.",
    newPemDown:'Generate new keypair down.',
    DeletePemOK:'Key pair be deleted.',
    SendEmailForDeletePem:'A email sent to your mail address. Please click [Reset] to reset System.',
    dataFormatError:"Looks had mistake data. It can't be continue.",
    htmlServerError_notSuccess:'Can not access local server, please check your network or restart local server.',
    keyPairPasswordErr:'Incorrect keypair password.',
    anotherAccess:'Someone try open Vpn.Email system config page. If that is know please ignored.',
    multiLogin: 'Oppps, Someone already open Vpn.Email control page.',
    have_keypair: "Error: Cant't generate new key pair. Please delete old key pair than do generate new key pair. "
},{
    warning:"警　告!",
    no_login:'請登入後再操作！',
    info:"信息",
    offline:'無網路可用，您的計算機似乎未連接互聯網。',
    UnknowErr: '未知錯誤，請再試',
    vpnEmailConnect: 'Vpn.Email服務器連接中!',
    vpnEmailDisconnect: '未連接 Vpn.Email服務器。',
    UnAllowAccess:'不被許可的訪問！',
	ECONNREFUSED: '指定端口連接被重置錯誤。有可能您所在網絡不支持或服務器不能在這個端口進行數據通訊，請另換端口試試。',
    vpnviaEmailSystemError:'Vpn.Email系統錯誤，重啟Vpn.Email後請再試。如連續發生，請重裝Vpn.Email系統。',
	'vpnvia.email-timeout': 'Vpn.Email服務器應答超時。有可能您所使用的Email服務商無法發送郵件到Vpn.Email域名，請嘗試使用其他Email。或Vpn.Email服務器忙碌，請再試。',
    hostCertError: 'IP證書錯誤，您有可能正在連接到一個假冒的服務器上，無法繼續。如果連續發生，請嘗試使用其他Email服務商',
    hostPortTimeOut: '指定端口連接超時，請檢查是否端口號是否正確',
    hostAuthTimeOut:'服務器登陸超時，請再試',
    cantDecryption:'提供的驗證郵件不能被解密，或不能被驗證，請檢查您的郵箱，如果有多封從Vpn.Email過來的郵件，請提供最後一封的內容。或刪除您的密鑰後，重新再試一次。',
    passwordErrMsg: '用戶名或密碼有誤! 請檢查您的Email帳號是否[<a target="_blank" href="https://kf.qq.com/faq/120322fu63YV130422mIrYnu.html">啟用IMAP</a>]。如果您的Email帳號設定了應用密碼和雙重驗證，你必須在密碼欄填入' +
		'［<a target="_blank" href="http://windows.microsoft.com/zh-cn/windows/app-passwords-two-step-verification">應用專用密碼</a>］',
    imapEnable: '您的Email賬號好像沒有啟用IMAP訪問功能，請進入Email服務商網站，選擇[<a target="_blank" href="https://kf.qq.com/faq/120322fu63YV130422mIrYnu.html">啟用IMAP</a>]訪問',
    hostAddrErr:'服務器IP不能獲得，請檢查服務器名稱是否有誤',
    networkOff:"客戶端從Internet斷開",
    networkOnLine:'客戶端連接著Internet',
    networkBack:"網絡故障排除",
    permitted:'錯誤：文件被鎖定，不能被操作！',
    anotherLogin:'錯誤：Vpn.Email已運行中，請輸入密碼後才能刪除。',
    fileCreateError:'文件創建錯誤，請檢查您的服務器操作系統。可能的原因是系統已無空間，或您沒有創建文件的權利。',
    newPemDown:'密鑰對創建完成！',
    DeletePemOK:'系統密鑰對已刪除。',
    SendEmailForDeletePem:'系統已發送一封系統重置的郵件到您的郵箱，請檢查您的郵箱，按郵件裡的［重置系統］按鈕來重新設置系統。',
    dataFormatError:'傳送到服務器的數據錯誤，您的操作不能完成！',
    htmlServerError_notSuccess:'本地服務器通訊錯誤,請檢查您的網絡或重啟本地服務器！',
    keyPairPasswordErr:'密鑰對密碼錯誤',
    anotherAccess:'Vpn.Email檢測到有他人試圖登錄登錄系統。如果是您了解的,請忽視!',
    multiLogin:'Vpn.Email設定頁面已經在其他瀏覽器打開！',
    have_keypair:'錯誤：系統已生成密鑰對，如需重新生成，請首先刪除原有的密鑰對！'
    
}]

enum lang1 { 'zh', 'ja', 'en', 'tw' }

let sock = io()
const socketEmit = ( socket: SocketIOClient.Socket, eventString: string, data: any, CallBack ) => {
    if ( !socket.connected )
        return setTimeout (() => {
            socketEmit ( socket, eventString, data, CallBack )
        }, 1000 * 5)
    socket.emit ( eventString, data, CallBack )
}

const lettersRegexp = /^[A-Za-z]+$/

const EmailRegexp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i
const numberRegexp = /^[0-9]+$/
let uniqueIDArray = []
//const LocalLanguageSystemInfomation = ko.observable ( systemInfomation );
const systemInfomationEvent = "systemInfomationEvent";

const initLanguageCookie = () => {
    let cc: string = $.cookie ( cookieName );
    
    if ( ! cc ) {
        cc = window.navigator.language;
    }

    if ( ! cc )
        cc = 'en';
        
    cc = cc.substr ( 0, 2 ).toLocaleLowerCase ();
    switch ( cc ) {
        case 'zh':
            break;
        case 'en':
            break;
        case 'ja':
            break;
        case 'tw':
            break
        default:
            cc = 'en';
    }
    $.cookie ( "langEH", cc, { expires: 180, path: '/' });
    $ ( "html" ).trigger ( 'languageMenu', cc );
    return cc;
}

const saveLanguageCooie = ( str: string ) => {
    $.cookie ( cookieName, str, { expires: 180, path: '/' });
}

const randString = ( n: number = 5 ) => {

    let possible: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let text = possible.charAt ( Math.floor ( Math.random() * (possible.length - 10)));

    for ( let i = 1; i < n; i++ ) {
        text += possible.charAt ( Math.floor ( Math.random() * possible.length ));
    }
    if ( uniqueIDArray.length > 0 && uniqueIDArray.lastIndexOf( text ) > 0 )
        text = this.randString ( n );
    return text;
}

const showNotify = ( error: string ) => {
    const lang = initLanguageCookie()
    const index = lang1 [ lang ]
    let time = new Date()
    /*
    let now1 = '<h6>' + time.toLocaleString () + '</h6>'
    let online = now1 + '<h6>' + LocalLanguageSystemInfomation ().networkBack + '</h6>'
    let offLine = now1 + '<h6>' + LocalLanguageSystemInfomation ().networkOff + '</h6>'
    */
    const show = !systemInfomation[0][error]
    $.Notify({ content : `<span class = 'ErrDetail' ve-data-bind="LocalLanguageSystemInfomation()['${error}']||LocalLanguageSystemInfomation().UnknowErr + '${error}'">${systemInfomation[index][error]||systemInfomation[index].UnknowErr + error}</span>` , 
        icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>', timeout: 7000,
        type : 'warning', shadow : true, keepOpen : show })

        /*
        case 'have_keypair': {
            $.Notify({ content : `<span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().multiLogin">${LocalLanguageSystemInfomation().have_keypair}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        
        case 'online': {
            $.Notify ({ content : stat ? online: offLine, 
              icon : stat ? '<span class="mif-wifi-full"></span>' : 
              `<span class="mif-wifi-mid fg-red"></span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>`,
              type : stat ? 'success':'warning', shadow : true, keepOpen : false })
        }
        break;
        case 'vpnviaEmailSystemError':
            $.Notify({ content : `<span data-bind="LocalLanguageSystemInfomation().vpnviaEmailSystemError">${LocalLanguageSystemInfomation().vpnviaEmailSystemError}</span>`, 
                icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
                type : 'alert', shadow : true, keepOpen : true })
        break;
        case 'pem-delete':{
            const detail = bData.data =='1'
                ? 'LocalLanguageSystemInfomation().DeletePemOK'
                : 'LocalLanguageSystemInfomation().SendEmailForDeletePem'
            $.Notify ({ content : `<span data-bind="${detail}">${eval(detail)}</span>`, 
              icon : '<span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'success', shadow : true, keepOpen : true })
        }
        break

        case 'permitted': {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().permitted">${LocalLanguageSystemInfomation().permitted}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        case 'multiLogin': {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().multiLogin">${LocalLanguageSystemInfomation().multiLogin}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        case 'fileCreateError': {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().fileCreateError">${LocalLanguageSystemInfomation().fileCreateError}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        
        case 'keyPairPasswordErr': {
             $.Notify({ content : `<span data-bind="LocalLanguageSystemInfomation().keyPairPasswordErr">${LocalLanguageSystemInfomation().keyPairPasswordErr}</span>`, 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'alert', shadow : true, keepOpen : true })
        }
        break;
        
        case 'UnAllowAccess': {
            $.Notify({ content : `<span data-bind="LocalLanguageSystemInfomation().UnAllowAccess">${LocalLanguageSystemInfomation().UnAllowAccess}</span>`, 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'alert', shadow : true, keepOpen : true })
        }
        break;
        
        case 'system-err':
        case 'server-err':{
              $.Notify({ content : `<span data-bind="LocalLanguageSystemInfomation().htmlServerError_notSuccess">${LocalLanguageSystemInfomation().htmlServerError_notSuccess}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'alert', shadow : true, keepOpen : true })
        }
        break;
        
        case 'data-format' : {
              $.Notify({ content :`<span data-bind="LocalLanguageSystemInfomation().dataFormatError">${LocalLanguageSystemInfomation().dataFormatError}</span>`, 
              icon : '<span class="mif-ambulance fg-yellow mif-ani-flash mif-ani-slow">',
              type : 'alert', shadow : true, keepOpen : true })
        }
        break;
        
        case 'passwordErrMsg' : {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().userNamePasswordErr">${LocalLanguageSystemInfomation().userNamePasswordErr}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow fg-red"></span>',
              shadow : true, keepOpen : true })
        }
        break;
        
        case 'hostAddrErr' : {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().hostNameAddressErr">${LocalLanguageSystemInfomation().hostNameAddressErr}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        
        case 'imapEnable' : {
            $.Notify({ content : `<span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().imapEnableErr">${LocalLanguageSystemInfomation().imapEnableErr}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        
        case 'hostAuthTimeOut' : {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().hostAuthTimeOut">${LocalLanguageSystemInfomation().hostAuthTimeOut}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        
        case 'hostPortTimeOut' : {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().hostPortTimeOut">${LocalLanguageSystemInfomation().hostPortTimeOut}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        
        case 'hostCertError' : {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().hostCertError">${LocalLanguageSystemInfomation().hostCertError}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'alert', shadow : true, keepOpen : true })
        }
        break;
        
		case 'ECONNREFUSED': {
			$.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().ECONNREFUSED">${LocalLanguageSystemInfomation().ECONNREFUSED}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'alert', shadow : true, keepOpen : true })
		}
		break;
        
        case 'UnknowErr': {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().UnknowErr">${LocalLanguageSystemInfomation().UnknowErr}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        
		case 'vpnvia.email-timeout': {
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().vpn_email_timeout">${LocalLanguageSystemInfomation().vpn_email_timeout}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        case 'active password error': 
        case 'cantDecryption':{
            $.Notify({ content : `<span>${bData.data}</span><span class = 'ErrDetail' data-bind="LocalLanguageSystemInfomation().cantDecryption">${LocalLanguageSystemInfomation().cantDecryption}</span>` , 
              icon : '</span><span class="mif-warning mif-ani-flash mif-ani-slow"></span>',
              type : 'warning', shadow : true, keepOpen : true })
        }
        break;
        */
}

const checkUrl = ( url: string, CallBack: ( err?, data?: boolean ) => void ) => {
    $.post ( '/api/testUrl',{ url: url }, ( data, status ) => {
        if (data == '-1') {
            CallBack (null, false)
        } else {
            CallBack (null, true) 
        }
    }).fail ( data => {
        //systemNotifyEvent ( 'system-err','' )
        CallBack ('err')
    })
}


//************************************************************************************************

module view_layout {

    export class InitEmailPool {
        
        /**
         *      check range
         *      @param num <string|number>
         *      @param start <number>
         *      @param stop <number>
         *      @return <boolean>
         */
        static range = (num: number | string, start: number, stop: number) => {
            const nn = typeof num === 'string'
                ? parseInt (num)
                : num
            return nn >= start && nn < stop
        }
	    //		account name
            //		Form data fields
            private settimeDefine = null;
            public emailAddress = ko.observable('')
            public emailAddressShowError = ko.observable (false)
            public password = ko.observable('')
            public passwordShowError = ko.observable (false)
            public iMapServerName = ko.observable('')
            public iMapServerLoginName = ko.observable('')
            public iMapServerLoginPassword = ko.observable('')
            public iMapServerPortNumber = ko.observable('')
            public SmtpServerName = ko.observable('')
            public SmtpServerLoginName = ko.observable('')
            public SmtpServerLoginPassword = ko.observable('')
            public SmtpServerPortNumber = ko.observable('')
            public sptmServerPortNumberError = ko.observable(false)
            public iMapServerPortNumberError = ko.observable(false)
            public smtpSecure = ko.observable(true)
            public iMapSecure = ko.observable(true)
            public smtpHostNameErr = ko.observable(false)
            public imapHostNameErr = ko.observable(false)
            
            //      Accordion title side show email account info
            public EmailAccount_show = ko.observable('')
                                    
            //		imap & smtp check running
            public emailAddreaaChecking = ko.observable ( false )	
            
            //		true when email input valid
            public emailAddressSuccess = ko.observable (false)
            public passwordSuccess = ko.observable (false)
            
            //		show Smtp Imap host detail setup tree 
            public showImapSmtpdetailTreeView = ko.observable (false)
            
            //		true when imap setup success
            public ImapCheckOK = ko.observable (false)
            public ImapCheckErr = ko.observable (false)
            public SmtpCheckErr = ko.observable (false)
            public SmtpCheckOK = ko.observable (false)
            public ProxyViaEmailConnect = ko.observable (false)
            public ProxyViaEmailConnectErr = ko.observable (false)
            public cancelProcessButtonShow = ko.observable (false)
            public VpnviaEmailCheckOK = ko.observable (false)
            //		did fill all fields
            public ImapSmtpReady = ko.observable (false)
            
            //		the root of InitEmailPool
            public parnet: KnockoutObservableArray <InitEmailPool> = null;
            
            //		select field data
            public imapPortArray = [ '143','443','993','other' ]
            public smtpPortArray = [ '25','465','587','994','2525','other' ]
            
            //      form showAccountType
            

            //  ProxyViaEmailConnectStep
            public ProxyViaEmailConnectStep = ko.observable (0);
            private EventUuid = uuid_generate ()
            public imapPortChecked = ko.observable ( '' )
            public smtpPortChecked = ko.observable ( '' )
            public showDeleteImapAccount = ko.observable ( false )
            
            public emailAccountWarning = ko.observable ( false )
            
		public everyThingCheckOk = ko.computed (() => {
			const imap = this.ImapCheckOK ()
				? 1 : 0
			const smtp = this.SmtpCheckOK()
				? 1 : 0
			const ProxyViaEmailConnect = this.ProxyViaEmailConnect ()
				? 1 : 0
				
			return ( imap + smtp + ProxyViaEmailConnect )
		})

        imapAuthenticationFailed = ko.observable(false)
        smtpAuthenticationFailed = ko.observable(false)
        nodeCollapsed = ko.observable(true)
        
        notify_Show = ko.observableArray ([])

        serverCheckStatus = ko.observable (0)
        
        emailAddreaaChecked = ko.observable ( false )             //  when imap & smtp check is OK
        
        emailAddressproblem = ko.observable ( '' )                //  return the error when have problem check imap or smtp
        
        
        /**
         * 
         *                      Get Imap server name from email address
         * 
         */
        
        private getDomainName = ( email: string ) => {
            
            let ret = email.split ('@');
            return ret.length > 1
                ? ret[1]
                : null
        }      

        public checkStep = 0;
        
        private checkSmtpImapAccountSetup = ( email: string ) => {
            if ( checkEmail ( email ).length ) {
                this.emailAddressSuccess ( false )
                this.ImapSmtpReady ( false )
                return true
            }
            
            this.emailAddressSuccess ( true )
            
            const data = getImapSmtpHost ( email )
            this.iMapServerName ( data.imap )
            this.iMapServerLoginName ( email )
            this.iMapSecure ( data.imapSsl )
			if ( ! this.imapPortChecked ())
				this.imapPortChecked (data.ImapPort.toString ())
            
            this.SmtpServerName ( data.smtp )
            this.SmtpServerLoginName ( email )
            this.smtpSecure ( data.smtpSsl )
			if ( !this.smtpPortChecked ())
            	this.smtpPortChecked (data.SmtpPort[0].toString ())
            //this.showImapSmtpdetailTreeView (true)
            if (this.passwordSuccess ())
                this.ImapSmtpReady ( true )
            return true
        }
        
        private checkSameAddressInArray = () => {
            var self = this
            var tt = 0
            for ( var t = 0; t < self.parnet().length; t++ ) {
                var n = self.parnet ()[t]
                if ( n.emailAddress() == self.emailAddress () ){
                    tt++
                }
            }
            if ( tt > 1 )
                return true
            return false
        }
		
		public form_emailPoolForm_delete = () => {
            
			sock.emit( 'deleteImapArray', viewLayout.emailPool()[0], (n) => {
                if ( ! n ) {
                    viewLayout.activePemForm (false);
                    viewLayout.sentActivePassword(false)
                    viewLayout.fromVpnViaEmailServer = null;
                    viewLayout.cleanUpEmailPool();
                    return
                    
                }
                showNotify ( n )
            });
            
		}
        
        /**
         * 
         *  Imap setup form submit
         * 
         */
        public form_emailPoolForm_submit = () => {
            //				reset view
            this.emailAccountWarning ( false )
            this.SmtpCheckErr ( false )
            this.ImapCheckErr ( false )
            this.ProxyViaEmailConnectErr ( false )
            this.SmtpCheckOK ( false )
            this.ImapCheckOK ( false )
            this.ProxyViaEmailConnect ( false )
            
            this.imapHostNameErr ( false )
            this.smtpAuthenticationFailed ( false )
            this.smtpHostNameErr ( false )
            this.imapAuthenticationFailed ( false )
            this.serverCheckStatus ( 0 )
            this.checkStep = 0;
			this.cancelProcessButtonShow ( false )
            this.checkSmtpImapAccountSetup ( this.emailAddress ())
            
            //		check email address valid
            if (!this.emailAddressSuccess()) {
                return 
            }
            this.ProxyViaEmailConnectStep ( 0 );
            this.emailAddreaaChecking ( true )
            viewLayout.emailAddreaaChecking_root ( true )
            
            //		reset notify show
            this.notify_Show ([])
            
            //		build data 
            const jsonData: IinputData = {
				
                account: this.account,
                password: this.password (),
                email: this.emailAddress (),
                imapServer: this.iMapServerName (),
                imapPortNumber: this.imapPortChecked () || this.iMapServerPortNumber (),
                imapUserName: this.iMapServerLoginName (),
                imapUserPassword: this.iMapServerLoginPassword (),
                smtpServer: this.SmtpServerName (),
                smtpPortNumber: this.smtpPortChecked () || this.SmtpServerPortNumber (),
                smtpUserName: this.SmtpServerLoginName (),
                smtpUserPassword: this.SmtpServerLoginPassword (),
                uuid: this.EventUuid,
                imapSsl: this.iMapSecure (),
                smtpSsl: this.smtpSecure (),
                Status: 0,
                publicKey: null,
				systemPassword: this.systemPassword,
				publicKey_id: null,
				serverMailBoxName: null,
                dummyData: null,
                VpnviaEmailCheckOK: false,
                power: null,
                machineID: null,
                imapConnect: null,
                remoteImapConnect: null,
                imapTested: false,
                smtpTested: false,
                runningContainerData: null
            }
			

            //      check smtp
            sock.emit ( 'testImapConnect', jsonData, err => {
                if ( err ) {
                    this.cancelProcessButtonShow ( true )
                    this.showImapSmtpdetailTreeView ( true )
                    
                    if ( this.checkStep === 2 )
                        this.emailAddreaaChecking ( false )
                        viewLayout.emailAddreaaChecking_root ( false )
                    
                    if ( /passwordErrMsg/.test( err )) {
                        this.passwordShowError ( true )
                        this.emailAddressShowError ( true )
                        
                    }
                    
                    if ( /hostPortTimeOut|hostAddrErr/.test ( err )) {
                        this.showImapSmtpdetailTreeView ( true )
                    }
                    showNotify ( err )
                    if ( this.checkStep == 0 )
                        return this.ImapCheckErr ( true )
                    if ( this.checkStep == 1 )
                        return this.SmtpCheckErr ( true )
                }
                setTimeout (() => {
                    this.cancelProcessButtonShow ( true )
                }, 1000 * 30 )
                    
            })
            
        }

        constructor ( private account: string, private systemPassword: string ) {

            //		email field after enter
            this.emailAddress.subscribe (( newValue: string ) => {
                this.passwordShowError ( false )
                this.emailAddressShowError ( false )
                this.showImapSmtpdetailTreeView ( false )
                this.checkSmtpImapAccountSetup ( newValue )
                
            })
            //			password field after enter
            this.password.subscribe (( newValue ) => {
                this.passwordShowError ( false )
                this.emailAddressShowError ( false )
                this.showImapSmtpdetailTreeView ( false )
                this.iMapServerLoginPassword ( newValue )
                this.SmtpServerLoginPassword ( newValue )
                if ( newValue.length ) {
                    this.passwordSuccess ( true )
                    if ( this.emailAddressSuccess() )
                        this.ImapSmtpReady ( true )
                    return true
                }
                this.passwordSuccess ( false )
                this.ImapSmtpReady ( false )
            })
            
            this.iMapServerPortNumber.subscribe (( newValue: string ) => {
                
                this.iMapServerPortNumberError ( false )
                
                if ( testNumber.isAcceptable ( newValue )) {
                    return InitEmailPool.range ( newValue, 1, 65535 )
                }
                
                this.iMapServerPortNumberError ( true )
            })
            
            this.SmtpServerPortNumber.subscribe (( newValue: string ) => {
                
                this.sptmServerPortNumberError (false)
                
                if ( testNumber.isAcceptable ( newValue )) {
                    return InitEmailPool.range ( newValue, 1, 65535 )
                }
                
                this.sptmServerPortNumberError ( true )
                
            })
            
            this.iMapServerName.subscribe (( newValue: string ) => {
                
                this.imapHostNameErr (false)
                
                const test = /^([a-zA-Z0-9]+(?:(?:\.|\-)[a-zA-Z0-9]+)+(?:\:\d+)?(?:\/[\w\-]+)*(?:\/?|\/\w+\.[a-zA-Z]{2,4}(?:\?[\w]+\=[\w\-]+)?)?(?:\&[\w]+\=[\w\-]+)*)$/
                
                if ( test.test ( newValue ))
                    return true
                    
                this.imapHostNameErr ( true )
                
            })
            
            this.iMapServerLoginName.subscribe ( n => {
                
                this.imapAuthenticationFailed ( false )
                
                return true
                
            })
            
            this.iMapServerLoginPassword.subscribe ( newValue => {
                
                this.smtpAuthenticationFailed ( false )
                
                return true
            })
        }

        public vpnEmailData ( vpnEmaildata: ISentMessage) {
            //          have empty data
            if ( ! vpnEmaildata || ! vpnEmaildata.region || ! vpnEmaildata.region.length )
                return;
            //          hide [imap] [smtp] [connect] 3 running show div
            this.ProxyViaEmailConnect ( true )
            //          hide running animation Preloaders
            this.emailAddreaaChecking ( false )
            viewLayout.emailAddreaaChecking_root ( false )
            //          hide cancel running Process Button
            this.cancelProcessButtonShow ( false )
            //          hide IMAP edit area
            this.VpnviaEmailCheckOK ( true )
            
        }
    
    }      
    /*****************************************************************************************************
     * 
     *
     * 
     * 
     ****************************************************************************************************/

    export class view {
        static tLang = ''
        pemButtonPanel_delete = $ ( '#pemButtonPanel_delete' )
        pemButtonPanel = $ ( '#pemButtonPanel' )
        
        //      init class
        constructor () {

            view.tLang = initLanguageCookie ()
            //self.pemButtonPanel_delete.hide ();
            this.languageIndex = ko.observable ( lang1 [ view.tLang ] )
            this.dataJson = ko.observable ( infoDefine [ this.languageIndex ()])
            this.home_index_view = ko.observable ( this.dataJson ().home_index_view )
            //          DEFINE INIT AREA
                this.logoutPanel_view = ko.observable (false);
                this.preloaderPasswordInput = ko.observable ( false )
                this.ErrorWindowInformation = ko.observable (systemInfomation)
                this.connectServerID = uuid_generate();
                this.languageList = ko.observableArray ( view.Menu [ view.tLang ])
                this.currentSelected = ko.observable ( this.languageList()[0] )
                this.info = ko.observable ( this.dataJson().info )
                this.config_index_view = ko.observable ( this.dataJson().config_index_view )
                this.btn = ko.observable ( this.dataJson ().btn )
                this.legal = ko.observable (this.dataJson().legal )
                this.passwordView = ko.observable ( this.dataJson ().password_view )
                this.input = ko.observable ( this.dataJson ().input )
                this.errorMessage = ko.observable ( this.dataJson ().errorMessage)
                this.cer = ko.observable ('')
                this.cer_date = ko.observable ('')
                this.DeleteCheckBoxchecked = ko.observable (false)
                this.systemSetup_systemPassword = ko.observable ('')
                this.SystemInformation = ko.observable ('')
                this.networkOnline = ko.observable (false)
                this.panel_success_password = ko.observable (false)
                this.components_ProxyViaEmail_addAnEmail = ko.observable ( this.dataJson().components_ProxyViaEmail_addAnEmail )
                this.alreadyInit = ko.observable (false)
                this.frame_keypair_active = ko.observable (true)
                this.multiLogin = ko.observable(false)
                this.delete_btn_view = ko.observable (false)
                this.panel_success_systemEmail = ko.observable (false)
                this.SystemAdministratorEmailAddress = ko.observable ('')
                this.SystemPassword_submitRunning = ko.observable (false)
                this.SystemAdministratorNickName = ko.observable ('')
                this.keyPairLengthSelect = ko.observable ('2048')
                this.Show_Ok_button = ko.observable (false)
                this.GlobalErrorItem = ko.observable ('')
                this.systemPasswordReady = ko.observable (false)
				this.activePemForm = ko.observable (false)
                this.emailPool = ko.observableArray ([])
                this.unLock_btn_view = ko.observable (false)
                this.isHeadingFixClick = ko.observable (false)
                this.SystemNickNameErrorItem = ko.observable ('')
                this.EmailAddressSuccess = ko.observable ( false )    //  email check
                this.SystemAdministratorNickNameItemError = ko.observable ( false )
                this.IMAP_Connect = ko.observable(false)
				this.activeEmailInputText = ko.observable('')
                this.activeEmailTextError = ko.observable (false)
				this.emailProviderListActive = ko.observable (false)
				this.appPasswordFrameActive = ko.observable (false)
                this.checkActiveEmailprocess = ko.observable(false)
                this.fromVpnViaEmailServer = null;
                this.isEmailVerification = ko.observable(false)
                this.sentActivePassword = ko.observable (false)
                this.showImapForm = ko.observable (false)
                this.showAccountType = ko.observable(false);
                this.AccountType = ko.observableArray([]);
                this.AccountTypeSelect = ko.observable('0');
                this.totalMonthPayment = ko.observable(0);
                this.totalYearPayment = ko.observable(0);
                this.freeAccount = ko.observable(false);
                this.showAccountSelectMenu = ko.observable(true);
                this.showPayment= ko.observable (false);
                this.paymantHtml = ko.observable('')
                this.selectMunthlyOrAnnual = ko.observable(false)
                this.eachGBprice = ko.observable('')
                this.totalSave = ko.observable(0);
                this.dayMaxTransfer = ko.observable ( '' );
                this.showPaymentView = ko.observable ( false );
                this.showMenuBarImap = ko.observable ( false );
                this.emailAddreaaChecking_root = ko.observable ( false );
                this.keyPairGenerateFormActive = ko.observable ( true );
                this.newKeyPairRunningCancelButtonShow = ko.observable ( false );
                this.LocalLanguageSystemInfomation = ko.observableArray ([])
                this.ImapInformationForm = ko.observable ( false  )
                this.cardNumber1 = ko.observable ('');
                this.cardNumber1_error = ko.observable (false);
                this.card_visa_show = ko.observable ( false );
                this.card_master_show = ko.observable ( false );
                this.card_discover_show = ko.observable ( false );
                this.card_diners_show = ko.observable ( false );
                this.card_jcb_show = ko.observable ( false );
                this.card_amex_show = ko.observable ( false );
                this.card_unknow_show = ko.observable ( true );
                this.cardNumber1Date = ko.observable ('');
                this.cardNumber1Cvc = ko.observable ('');
                this.cardNumberDate_error = ko.observable ( false );
                this.cardNumberDate_success = ko.observable ( false );
            
            //
            
            EmailSuppliers.forEach ( a => checkUrl ( a.linkButton, ( err, data ) => {
                if ( err ) {
                    return 
                }
                a.canAccess ( data )
            }))

            this.systemSetup_systemPassword ($.cookie ( 'Vpn.Email' ))

            sock.on ( 'online', ()  => {
                showNotify ('networkOnLine')
                //showNotify ( err )
            })

            sock.on ( 'offline', () => {
                showNotify ('networkOff')
            })

            sock.on ( 'NewKeyPairRunning', () => {
                this.SystemPassword_submitRunning ( true )
            })

            sock.on ( 'deletePassword', () => {
                this.panel_success_password ( false );
                this.delete_btn_view ( false);
                this.Show_Ok_button ( true );
                this.systemPasswordReady ( false );
                this.alreadyInit ( false );
                this.activePemForm ( false );
                this.showAccountType ( false );
                this.cleanUpEmailPool ()
                this.frame_keypair_active ( true )
                this.keyPairGenerateFormActive ( true )
            })

            sock.on ( 'cancelCreateKeyPair', () => {
                this.SystemPassword_submitRunning ( false )
                this.alreadyInit ( false )
                this.systemPasswordReady ( false )
                this.frame_keypair_active ( true )
                this.newKeyPairRunningCancelButtonShow ( false )
                this.delete_btn_view ( false )
            })

            sock.on ( 'NewKeyPair-CallBack', keyPair => {
                this.SystemPassword_submitRunning ( false )
                this.alreadyInit ( true )
                this.PemDown ( keyPair );
            })
            
            sock.emit ( 'first', this.systemSetup_systemPassword(), ( err, data: ISockSession ) => {
                if ( err )
                    return showNotify ( err.message )
                this.frame_keypair_active ( true )
                this.PemDown ( data.keyPair )
                if ( data.newKeyPairProcessRunning ) {
                    this.panel_success_systemEmail ( false )
                    this.EmailAddressSuccess ( true )
                    this.SystemPassword_submitRunning ( true )
                    return
                }
                if ( data.keyPair.keyPasswordOK ) {
                    this.keyPairGenerateFormActive (false)
                    this.alreadyInit ( true )
                    this.systemPasswordReady ( true )
                    this.showImapForm ( true )
                    if ( data.imapArray && data.imapArray.account ) {
                        this.addNewEmailAddressfromRet ( data.imapArray )
                        if ( data.vpnServerConnectData ) {
                            this.afterProcessGotDataFromVpnEmail ( data.vpnServerConnectData )
                        }
                        return
                    }
                    this.cleanUpEmailPool ();
                }
            })

            sock.on ( 'email', ( data: ISentMessage ) => {

                this.afterProcessGotDataFromVpnEmail ( data )
            })

            sock.on ( 'testImapOK', () => {
                this.emailPool()[0].ImapCheckOK  ( true )
                this.emailPool()[0].checkStep +=1
            })
            
            sock.on ( 'testSmtpOK', () => {
                this.emailPool()[0].SmtpCheckOK ( true )
                this.emailPool()[0].checkStep +=1
            })

            sock.on ( 'sentMailOK', () => {
                this.emailPool()[0].ProxyViaEmailConnectStep ( 2 )
            })

            this.SystemAdministratorEmailAddress.subscribe ( newValue => {

                var email = newValue
                
                if ( checkEmail ( email ).length ) {
                    this.EmailAddressSuccess (false)
                    return true
                }
				
                this.EmailAddressSuccess ( true )
				
                if ( ! this.SystemAdministratorNickName ().length ){
                    this.SystemAdministratorNickName ( getNickName ( email ))
                }
                
                return true
                
            })     //   end of SystemAdministratorEmailAddress.subscribe
            
            this.SystemAdministratorNickName.subscribe ( newValue => {
                if ( newValue.length > 0 ) {
                    this.SystemAdministratorNickNameItemError ( false );
                    return true;
                } else {
                    this.SystemAdministratorNickNameItemError ( true );
                }
            });

            sock.on ( 'vpnEmailOnline', online => {
                this.networkOnline ( online )
                //this.emailPool()[0].VpnviaEmailCheckOK (online)
                if ( online )
                    return showNotify ( 'vpnEmailConnect' )
                    
                showNotify ( 'vpnEmailDisconnect' )
            })

            //              Card expand process
            this.cardNumber1Date.subscribe ( newValue => {
                this.cardNumber1CvcHasFocus ( false )
                const newValueLength = newValue.length
                const move = newValue.length - this.cardNumber1DateLength > 0
                this.cardNumber1DateLength = newValue.length
                const oldValue = newValue.substr ( 0, newValueLength -1 )
                const newChar =  newValue.substr ( newValueLength - 1, newValueLength )
                const year = parseInt ( new Date().getFullYear().toString().substr ( 2, 2 ))
                const _newValueSplit = newValue.split ( '/' )
                const _temp = parseInt ( _newValueSplit [1]) >= year 
                const _temp1 = parseInt ( _newValueSplit [1]) > year
                const _month = new Date().getMonth() + 1
                const _nowMonth = parseInt ( _newValueSplit [0] )
                const _monthL =  _nowMonth < _month
                
                //      back
                if ( ! move ) {
                    if ( newValueLength == 2 )
                        this.cardNumber1Date ( oldValue )
                    return true
                }
                if ( /\D/.test ( newChar ) || newValueLength > 5 ) {
                    if ( newChar === '/')
                        return true
                    
                    this.cardNumber1Date ( oldValue )

                    return false
                }

                if ( newValueLength === 1 && ! ( newChar === '0' || newChar === '1' ) ||
                    newValueLength === 2 && ! ( /^(1[0-2]|0)/.test ( newValue ) ) || 
                    newValueLength === 4 &&  newChar === '0' ) {
                    this.cardNumber1Date ( oldValue )
                    return false
                }

                if ( newValueLength === 5 ) {
                    if ( _monthL && ! _temp1 ) {
                        this.cardNumberDate_error ( true )
                        return true
                    }

                    this.cardNumberDate_success ( true )
                    this.cardNumber1CvcHasFocus ( true )
                    return true
                }
                if ( newValueLength == 2) {
                    this.cardNumber1Date ( this.cardNumber1Date () + '/' )
                }

            })

            //              Card CVC input process
            this.cardNumber1Cvc.subscribe ( newValue => {
                const newValueLength = newValue.length
                const move = newValue.length - this.cardNumber1DateLength > 0
                this.cardNumber1DateLength = newValue.length
                const oldValue = newValue.substr ( 0, newValueLength -1 )
                const newChar =  newValue.substr ( newValueLength - 1, newValueLength )

                if ( /\D/.test ( newChar ) || newValueLength > 4 ) {
                    
                    this.cardNumber1Cvc ( oldValue )

                    return false
                }

                if ( newValueLength > 2 ) {
                    this.cardNumber1Cvc_success ( true )
                    return true
                }

                
            })

            //              Card Number INPUT process
            this.cardNumber1.subscribe ( newValue => {

                const newValueLength = newValue.length
                const move = newValue.length - this.cardNumber1Length > 0
                this.cardNumber1Length = newValue.length
                const oldValue = newValue.substr ( 0, newValueLength -1 )
                const newChar =  newValue.substr ( newValueLength - 1, newValueLength )

                //      back
                if ( ! move ) {
                    if ( newValueLength == 4 || newValueLength == 9 || newValueLength == 14 )
                        this.cardNumber1 ( oldValue )
                    return true
                }
                if ( /\D/.test ( newChar ) || 
                    (this.card_amex_show() || this.card_diners_show () && ! /^5/.test ( newValue ) || this.card_jcb_show () && ! /^35/.test ( newValue )) && newValueLength > 17 ||
                    newValueLength > 19 ) {
                    if ( newChar === '-')
                        return true
                    
                    this.cardNumber1 ( oldValue )

                    return false
                }
                if ( (this.card_visa_show () || this.card_amex_show () || this.card_master_show () || this.card_unknow_show ()) && 
                    ((this.card_amex_show() || this.card_diners_show () && ! /^5/.test ( newValue ) || this.card_jcb_show () && ! /^35/.test ( newValue )) && newValueLength === 17 ||
                    newValueLength === 19 )) {
                        this.cardNumber1_success ( true )
                        this.cardNumber1DateHasFocus ( true )
                        return true
                    }

                if ( newValueLength == 4 || ! this.card_amex_show() && newValueLength == 9 || ! this.card_amex_show() && newValueLength == 14 
                    || this.card_amex_show() && newValueLength == 11 )
                    this.cardNumber1 ( this.cardNumber1 () + '-' )

                this.resetAllCardIcon ()

                if ( /^4/.test ( newValue )) {
                    this.card_visa_show ( true )
                    return true
                }
                    
                if ( /^5[1-5]|^222[1-9]|^22[3-9]|^2[3-6]|^27[01]|^2720/.test ( newValue )) {
                    this.card_master_show ( true )
                    return true
                }
                if ( /^3[47]/.test ( newValue )) {
                    this.card_amex_show ( true )
                    return true
                }

                if ( /^30[0-5]|^3[68]/.test ( newValue ) ) {
                    this.card_diners_show ( true )
                    this.cardNumber1_success ( false )
                    this.cardNumber1_error ( true )
                    return true
                }

                if ( /^6(?:011|5)/.test ( newValue )) {
                    this.card_discover_show ( true )
                    this.cardNumber1_success ( false )
                    this.cardNumber1_error ( true )
                    return true
                }
                
                if ( /^2131|^1800|^35/.test ( newValue )) {
                    this.card_jcb_show ( true )
                    this.cardNumber1_success ( false )
                    this.cardNumber1_error ( true )
                    return true
                }

                this.card_unknow_show ( true )
                return true
            })
        }
        private resetAllCardIcon () {
            this.card_amex_show ( false )
            this.card_diners_show ( false )
            this.card_discover_show ( false )
            this.card_jcb_show ( false )
            this.card_master_show ( false )
            this.card_unknow_show ( false )
            this.cardNumber1_error ( false )
            this.card_visa_show ( false )
        }
         //      Language select menu shows
        private connectServerID: string;
        public currentSelected: KnockoutObservable < any >
		//      Language menu show                           
        static Menu = {
            'zh':[{
                LanguageJsonName: 'zh',
                showName: '简体中文',
                icon: 'flag-icon-cn'
            },
            {
                LanguageJsonName: 'en',
                showName: '英文/English',
                icon: 'flag-icon-gb'
            },
            {
                LanguageJsonName: 'ja',
                showName: '日文/日本語',
                icon: 'flag-icon-jp'
            },{
                LanguageJsonName: 'tw',
                showName: '繁体字中文/正體字中文',
                icon: 'flag-icon-tw'
            }],
            'ja': [{
                LanguageJsonName: 'ja',
                showName: '日本語',
                icon: 'flag-icon-jp'
            },
            {
                LanguageJsonName: 'en',
                showName: '英語/English',
                icon: 'flag-icon-gb'
            },
            {
                LanguageJsonName: 'zh',
                showName: '簡体字中国語/简体中文',
                icon: 'flag-icon-cn'
            },{
                LanguageJsonName: 'tw',
                showName: '繁体字中国語/正體字中文',
                icon: 'flag-icon-tw'
            }],
            'en': [{
                LanguageJsonName: 'en',
                showName: 'English',
                icon: 'flag-icon-gb'
            },
            {
                LanguageJsonName: 'ja',
                showName: 'Japanese/日本語',
                icon: 'flag-icon-jp'
            },
            {
                LanguageJsonName: 'zh',
                showName: 'Simplified Chinese/简体中文',
                icon: 'flag-icon-cn'
            },
            {
                LanguageJsonName: 'tw',
                showName: 'Traditional Chinese/正體字中文',
                icon: 'flag-icon-tw'
            }],
            'tw':[
            {
                LanguageJsonName: 'tw',
                showName: '正體字中文',
                icon: 'flag-icon-tw'
            },{
                LanguageJsonName: 'en',
                showName: '英文/English',
                icon: 'flag-icon-gb'
            },
            {
                LanguageJsonName: 'ja',
                showName: '日文/日本語',
                icon: 'flag-icon-jp'
            },
            {
                LanguageJsonName: 'zh',
                showName: '簡體字中文/简体中文',
                icon: 'flag-icon-cn'
            }]
        }
    //		true when user finished key pair or enter volid password
		public systemPasswordReady: KnockoutObservable < boolean >
		//		email provate list panel active
		public emailProviderListActive: KnockoutObservable < boolean >
		//		app password help panel active
		public appPasswordFrameActive: KnockoutObservable < boolean >
        //      alreadyInit
        public alreadyInit: KnockoutObservable < boolean >;
        public multiLogin: KnockoutObservable < boolean >;
        public frame_keypair_active: KnockoutObservable < boolean >;
        //      smtp Imap Setup Pool
        public emailPool: KnockoutObservableArray < InitEmailPool >;
        public showImapForm: KnockoutObservable < boolean>;
		//		activePemForm
		public activePemForm: KnockoutObservable < boolean >;
        public ErrorWindowInformation: KnockoutObservable < any >;
        //      iMap connect status
        public IMAP_Connect: KnockoutObservable < boolean >;
        public languageList: KnockoutObservableArray < any >                                
        public dataJson: KnockoutObservable < any >
        public SystemPassword_submitRunning: KnockoutObservable < boolean >
        public home_index_view: any;
        public config_index_view: any;
        public info: any;
        public keyPairLengthSelect: KnockoutObservable < string >;
        public legal: any;
        public btn: any;
        public passwordView: any;
        public activeEmailTextError: KnockoutObservable < boolean >;
        public input: any;
        public errorMessage: any;
        public components_ProxyViaEmail_addAnEmail: any;
        public cer: any;
        public cer_date:KnockoutObservable < string >;
        public systemSetup_systemPassword: KnockoutObservable < string >;
        public SystemAdministratorNickName: KnockoutObservable < string >;
        public panel_success_password: KnockoutObservable < boolean >;
        public languageIndex: KnockoutObservable < number >;
        public activeEmailInputText: KnockoutObservable < string >;
        public networkOnline: KnockoutObservable < boolean >;
        public delete_btn_view: KnockoutObservable < boolean >;
        public panel_success_systemEmail: KnockoutObservable < boolean >;
        public SystemAdministratorEmailAddress: KnockoutObservable < string >;
        public Show_Ok_button: KnockoutObservable < boolean >;
        public GlobalErrorItem: KnockoutObservable < string >;
        public SystemNickNameErrorItem: KnockoutObservable < string >;
        public SystemInformation: KnockoutObservable < string >;
        public SystemAdministratorNickNameItemError: KnockoutObservable < boolean >;
        public EmailAddressSuccess: KnockoutObservable < boolean >;
        public DeleteCheckBoxchecked: KnockoutObservable < boolean >;
        public unLock_btn_view: KnockoutObservable < boolean >;
        public checkActiveEmailprocess: KnockoutObservable < boolean >;
        public emailAddreaaChecking_root: KnockoutObservable < boolean >;
        //     view show Email verified information
        public isEmailVerification: KnockoutObservable<boolean>;
        public isHeadingFixClick:KnockoutObservable<boolean>;
        public fromVpnViaEmailServer: ISentMessage;
        public sentActivePassword: KnockoutObservable<boolean>;
        public logoutPanel_view:KnockoutObservable<boolean>;
        public showAccountType :KnockoutObservable<boolean>;
        public AccountType: KnockoutObservableArray < IAccountType >;
        public AccountTypeSelect: KnockoutObservable<string>;
        public totalMonthPayment:KnockoutObservable<number>;
        public totalYearPayment: KnockoutObservable<number>;
        public freeAccount: KnockoutObservable<boolean>;
        public showAccountSelectMenu: KnockoutObservable<boolean>;
        public showPayment: KnockoutObservable<boolean>;
        public paymantHtml: KnockoutObservable<string>;
        public selectMunthlyOrAnnual: KnockoutObservable<boolean>;
        public eachGBprice: KnockoutObservable<string>;
        public totalSave:KnockoutObservable<number>;
        public dayMaxTransfer:KnockoutObservable<string>;
        public showPaymentView: KnockoutObservable<boolean>;
        public showMenuBarImap: KnockoutObservable<boolean>;
        public keyPairGenerateFormActive: KnockoutObservable < boolean >;
        public newKeyPairRunningCancelButtonShow : KnockoutObservable < boolean >;
        public preloaderPasswordInput: KnockoutObservable < boolean >;
        public LocalLanguageSystemInfomation: KnockoutObservableArray <any>;
        public ImapInformationForm: KnockoutObservable < boolean >;
        public totalmayment = 0;
        public cardNumber1: KnockoutObservable < string >;
        public cardNumber1_error: KnockoutObservable < boolean >;
        public cardNumber1_success:  KnockoutObservable < boolean > = ko.observable ( false )
        private cardNumberTemp = ''
        public card_visa_show: KnockoutObservable < boolean>;
        public card_master_show: KnockoutObservable < boolean >;
        public card_amex_show: KnockoutObservable < boolean >;
        public card_jcb_show: KnockoutObservable < boolean >;
        public card_discover_show: KnockoutObservable < boolean >;
        public card_diners_show: KnockoutObservable < boolean >;
        public card_unknow_show: KnockoutObservable < boolean >;
        private keyTime = null;
        private cardNumber1Length = 0;
        public cardNumber1Date: KnockoutObservable < string >;
        public cardNumber1Cvc: KnockoutObservable < string >;
        public cardNumberDate_error: KnockoutObservable < boolean >;
        public cardNumberDateFormat_error: KnockoutObservable < boolean > = ko.observable ( false );
        public cardNumberDate_success: KnockoutObservable < boolean >;
        public cardNumber1DateHasFocus: KnockoutObservable < boolean > = ko.observable ( false );
        public cardNumber1CvcHasFocus: KnockoutObservable < boolean > = ko.observable ( false );
        private cardNumber1DateLength = 0;
        public cardNumber1Cvc_success: KnockoutObservable < boolean > = ko.observable ( false );
        public cardNumber1Cvc_error: KnockoutObservable < boolean > = ko.observable ( false );
        public cardNumber1Format_error: KnockoutObservable < boolean > = ko.observable ( false );
        public cardInformationForm: KnockoutObservable < boolean > = ko.observable ( true );
        public paymentUserInformaton: KnockoutObservable < boolean > = ko.observable ( false );
        public paymentUserInformationButton: KnockoutObservable < boolean > = ko.observable ( this.cardNumber1_success() && this.cardNumber1Cvc_success() && this.cardNumberDate_success());
        public cardName_error: KnockoutObservable < boolean > = ko.observable ( false );
        public caedName_success: KnockoutObservable < boolean > = ko.observable ( false );
        public cardName: KnockoutObservable < string > = ko.observable ('')
        public cardPostCode: KnockoutObservable < string > = ko.observable ('')
        public cardPostCode_error: KnockoutObservable < boolean > = ko.observable ( false );
        public cardPostCode_success: KnockoutObservable < boolean > = ko.observable ( false );
        public cardAddress: KnockoutObservable < string > = ko.observable ('')
        public cardAddress_error: KnockoutObservable < boolean > = ko.observable ( false );
        public cardAddress_success: KnockoutObservable < boolean > = ko.observable ( false );
        public cardTelphone: KnockoutObservable < string > = ko.observable ('');
        public cardTelphone_error: KnockoutObservable < string > = ko.observable ('');
        public cardTelphone_success: KnockoutObservable < string > = ko.observable ('');


    //
        /**
         *      create new key pair 
         *      @param SystemAdministratorEmailAddress <string>
         *      @param SystemAdministratorNickName <string>
         *      @paramsystemSetup_systemPassword <string>
         */
        public form_AdministratorEmail_submit = () => {

            //self.SystemEmailErrorItem ( '' )
            this.panel_success_systemEmail ( false )
            this.EmailAddressSuccess ( true )
            let email = this.SystemAdministratorEmailAddress ()
            
          
            //   check email
            
            if ( checkEmail ( email ).length ) {
                this.EmailAddressSuccess ( false )
                return false
            }
            //    check nick name
            if (! this.SystemAdministratorNickName ().length ){
                return false
            }
            
            //    check password
            if ( this.systemSetup_systemPassword ().length < 5 ) {
                return false
            }

            this.SystemPassword_submitRunning ( true )
            this.newKeyPairRunningCancelButtonShow ( true )


            const sendData: INewKeyPair = {
                password: this.systemSetup_systemPassword (),
                keyLength: this.keyPairLengthSelect (),
                nikeName: this.SystemAdministratorNickName (),
                email: email

            }

            $.removeCookie ( 'Vpn.Email' )
            
            sock.emit ( 'NewKeyPair', sendData, ( err ) => {

                if ( err ) {
                    return showNotify ( err.message )
                }
                this.keyPairGenerateFormActive ( false )
                this.ImapInformationForm ( true )
                this.systemPasswordReady ( true )
                this.frame_keypair_active ( false )
                this.cleanUpEmailPool ();
                $.cookie ( 'Vpn.Email', this.systemSetup_systemPassword ())
            })

            return false       //    ！！！！，Page will reflash if return true;
            
        }
		
		/**
		 * 		emailProviderListShowClick
		 */
		public providerListShowClick = () => {
			this.emailProviderListActive ( ! this.emailProviderListActive ())
		}
        
		/**
		 * 		appPasswordFrameActiveClick
		 */
		public appPasswordFrameActiveClick = () => {
			this.appPasswordFrameActive (! this.appPasswordFrameActive ())
		}

        private afterProcessGotDataFromVpnEmail ( vpnData: ISentMessage ) {
            if ( ! vpnData || ! vpnData.region || !vpnData.region.length )
                return 
            this.emailPool()[0].vpnEmailData ( vpnData )
            this.AccountType ( vpnData.accountTypeList )
            if ( ! vpnData.active ) {

                this.activePemForm ( true )
                this.sentActivePassword ( false )
                return 
            } 
            this.ImapInformationForm ( false )
            this.isEmailVerification ( true )

            this.showAccountType ( true )
            this.activePemForm ( false )
            
                
        }



        /**
         *          unlock the system key pair
         *          param systemSetup_systemPassword <string>
        */
        public checkPemPassword = () => {
            this.preloaderPasswordInput ( true )
            this.SystemInformation ( '' )
            this.unLock_btn_view ( false )
            let password = this.systemSetup_systemPassword ()
             
            if ( ! password.length ) {
                return this.SystemInformation ('SystemPasswordError')
            }
            //      show preloader when login
            
	        sock.emit ( 'first', password, ( err, data: ISockSession ) => {
                this.preloaderPasswordInput ( false )
                if ( err )
                    return showNotify ( err )
                
                if ( ! data.keyPair.keyPasswordOK ) {
                    return this.SystemInformation ( 'SystemPasswordError' )
                }
                this.keyPairGenerateFormActive ( false )
                this.systemPasswordReady ( true )
                this.showImapForm ( true )
                if ( data.imapArray && data.imapArray.account ) {
                    this.addNewEmailAddressfromRet ( data.imapArray )
                    if ( data.vpnServerConnectData ) {
                        return this.afterProcessGotDataFromVpnEmail ( data.vpnServerConnectData )
                    }
                    return
                   
                }
                this.cleanUpEmailPool ();
                

	        })
            
        } 

        /*****************************************************************************************************
         * 
         *                  finished create pem
         * 
         ****************************************************************************************************/
        public deleteCheckBoxClick () {
            if( ! this.DeleteCheckBoxchecked ()){
                this.delete_btn_view ( ! this.delete_btn_view ())
                //this.DeleteCheckBoxchecked(false);
                
            }
            return true;
        }
        
        /**
         *      show key pair information
         *      @param data <iCer>
         */
        private PemDown = ( data: IKeyInformation ) => {
            if ( data && data.privateKeyUTF8 && data.privateKeyUTF8.length ) {
                this.SystemPassword_submitRunning (false)
                this.alreadyInit (true)
                
                this.cer ( data )
                var d = new Date ( data.createDate ).toLocaleString ()
                this.cer_date ( d )
                this.SystemAdministratorEmailAddress ( data.email )
            }
            
            
        }

        /*****************************************************************************************************
         * 
         * 
         *              Add a new service email address
         * 
         * 
         ****************************************************************************************************/
        public addNewEmailAddress = () => {
            var self = this
            var yy = new InitEmailPool ( self.SystemAdministratorEmailAddress(), self.systemSetup_systemPassword ())
            yy.parnet = self.emailPool
            self.emailPool.unshift (yy)
        }
        
        public checkActiveEmailSubmit = () => {

            //      hide error area
            this.activeEmailTextError ( false )

            const text = this.activeEmailInputText ()
            if ( ! /^-----BEGIN PGP MESSAGE-----((\r|\n|\r\n).*)+(\r|\n)-----END PGP MESSAGE-----/.test ( text )){
                this.activeEmailTextError ( true )
                return false
            }

            //          show Preloaders area
            this.checkActiveEmailprocess ( true )

            sock.emit ( 'sendActivePassword', text, n => {
                this.checkActiveEmailprocess ( false )
                if ( n && typeof n === 'string' ) {
                    if ( /isDecrypted/.test ( n )) {
                        this.activeEmailTextError ( true )
                        return //smtpImapCheckErr('cantDecryption', '')
                    }
                }

                this.sentActivePassword ( true )
                this.activePemForm ( false )
            })

        }

        public cleanUpEmailPool = () => {
            if (this.emailPool () && this.emailPool().length)
                this.emailPool.removeAll ()
            this.addNewEmailAddress ()
            this.showImapForm ( true )
        }

        public selectMunthlyOrAnnualClick ( index, data ) {
            this.AccountTypeSelect ( index )
            const y = index();
            if ( y === 0 ) {
                this.freeAccount ( true )
                this.selectMunthlyOrAnnual ( false )
                this.dayMaxTransfer ( data.detail )
            } else {
                
                this.freeAccount ( false )
                this.selectMunthlyOrAnnual ( true )
            }
            this.totalMonthPayment ( data.price )
            this.totalYearPayment ( data.annual )
            this.eachGBprice ( data.over_transfer_fee )
            this.totalSave( parseFloat ( data.price ) * 100 * 12/100 - parseFloat ( data.annual ) * 100/100 )
            const transfer = data.day_max_transfer;
            if ( transfer ) {
                //this.dayMaxTransfer(this.passwordView().everyDayTransfer + transfer+'MB')
            } else
                this.dayMaxTransfer ( this.passwordView ().everyDayTransfer + this.passwordView ().noMaxTransferEachDay )
        }

        public AccountTypeSelectClick ( Monthly: boolean ) {
            this.totalmayment = ( Monthly )
                ? this.totalMonthPayment ()
                : this.totalYearPayment ()


            this.showPaymentView ( true )
            
        }


        /**
         * 
         * 
         *          Add new service email from IinputData
         * 
         */
        public addNewEmailAddressfromRet ( ret: IinputData ) {
             var yy = new InitEmailPool ( this.SystemAdministratorEmailAddress (), this.systemSetup_systemPassword ())
             yy.parnet = this.emailPool
             yy.iMapServerName ( ret.imapServer )
             yy.iMapServerPortNumber (ret.imapPortNumber.toString ())
             yy.iMapServerLoginName (ret.imapUserName)
             yy.iMapServerLoginPassword (ret.imapUserPassword)
             yy.iMapSecure ( ret.imapSsl )
             yy.imapPortChecked ( ret.imapPortNumber.toString ())
             yy.SmtpServerName ( ret.smtpServer )
             yy.smtpPortChecked ( ret.smtpPortNumber.toString ())
             yy.SmtpServerLoginName ( ret.smtpUserName )
             yy.SmtpServerLoginPassword ( ret.smtpUserPassword )
             yy.smtpSecure ( ret.smtpSsl )
             yy.SmtpServerPortNumber ( ret.smtpPortNumber.toString ())
             yy.emailAddress ( ret.email )
             yy.serverCheckStatus ( ret.Status )
             yy.password ( ret.password )
             yy.VpnviaEmailCheckOK ( ret.VpnviaEmailCheckOK )
             
             
             this.emailPool.unshift ( yy )
             
        }
         
        public CancelCreateKeyPair () {
            sock.emit ('cancelCreateKeyPair')
        }

        /**
         *          Do delete Password
         */
        public deletePasswordNext = () => {

            sock.emit ( 'deletePassword', session => {
                this.delete_btn_view ( ! this.delete_btn_view ());

                if ( typeof session === 'string' && session.length ) {
                    return showNotify ( session )
                }
                this.panel_success_password ( false );
                this.delete_btn_view ( false);
                this.Show_Ok_button ( true );
                this.systemPasswordReady ( false );
                this.alreadyInit ( false );
                this.activePemForm ( false );
                this.showAccountType ( false );
                this.cleanUpEmailPool ()
                this.frame_keypair_active ( true )
                this.keyPairGenerateFormActive ( true )

            })
        }

        /*
        public totalProblem = ko.computed (() => {
            var self = this;
            var total = self.stat ().item1 ? 0 : 1;
            total += self.stat ().item2 ? 0 : 1;
            total += self.stat ().item5 ? 0 : 1;
            return total;
        })
        */
        /**
         *          Language nemu select a new Language
         */
        public selectItem = ( that, site: languageMenu ) => {
            if ( this.currentSelected().LanguageJsonName != site.LanguageJsonName ) {
                view.tLang = site.LanguageJsonName
                saveLanguageCooie ( site.LanguageJsonName )
                this.languageIndex ( lang1 [ view.tLang ] )
                this.dataJson ( infoDefine [ this.languageIndex ()])
                this.home_index_view ( this.dataJson ().home_index_view )
                this.languageList ( view.Menu [ view.tLang ]);
                this.currentSelected ( this.languageList()[0] );
                this.info = this.dataJson().info
                this.config_index_view (this.dataJson().config_index_view )
                this.btn ( this.dataJson().btn )
                this.legal ( this.dataJson().legal )
                this.passwordView ( this.dataJson ().password_view )
                this.input( this.dataJson ().input )
                this.errorMessage ( this.dataJson().errorMessage )
                this.LocalLanguageSystemInfomation ( systemInfomation [ this.languageIndex()])
                this.components_ProxyViaEmail_addAnEmail ( this.dataJson ().components_ProxyViaEmail_addAnEmail )
                $("html").trigger ( 'languageMenu', view.tLang )
                changeNotifyLanguage ()
            }
            
        }

        //          Card Number Onblur
        public cardNumber1Onblur = () => {
            const value = this.cardNumber1()
            const length = value.length
            this.cardNumber1_success ( false )
            this.cardNumber1Format_error ( false )
            this.cardNumber1_error ( false )
            if (( this.card_visa_show () || this.card_amex_show () || this.card_master_show () || this.card_unknow_show ()) && 
                (( this.card_amex_show() || this.card_diners_show () && ! /^5/.test ( value ) || this.card_jcb_show () && ! /^35/.test ( value )) && length !== 17 ||
                length !== 19 )) {
                    this.cardNumber1Format_error ( true )
                    return
                }
            this.cardNumber1_success ( true )
            this.paymentUserInformationButton ( this.cardNumber1_success() && this.cardNumber1Cvc_success() && this.cardNumberDate_success())
        }

        //          CVC 
        public cardNumber1CvcOnblur = ( event ) =>{
            if ( this.cardNumber1Cvc().length > 0 && this.cardNumber1Cvc().length < 3 ) {
                this.cardNumber1Cvc_error ( true )
                this.cardNumber1Cvc_success ( false )
                
                return
            }

            this.cardNumber1Cvc_error ( false )
            this.cardNumber1Cvc_success ( this.cardNumber1Cvc().length > 0 )
            this.paymentUserInformationButton ( this.cardNumber1_success() && this.cardNumber1Cvc_success() && this.cardNumberDate_success())
        }

        //          Date 
        public cardNumber1DateOnblur = ( event ) => {
            this.cardNumberDate_error ( false )
            const length = this.cardNumber1Date().length
            if ( length === 0 ) {
                this.cardNumberDate_success ( false )
                this.cardNumberDateFormat_error ( false )
                this.cardNumberDate_error ( false )
                return
            }
            if ( length < 5 ) {
                this.cardNumberDate_success ( false )
                this.cardNumberDateFormat_error ( true )
                return
            }

            const newValue = this.cardNumber1Date()
            const year = parseInt ( new Date().getFullYear().toString().substr ( 2, 2 ))
            const _newValueSplit = newValue.split ( '/' )
            const _temp = parseInt ( _newValueSplit [1]) >= year 
            const _temp1 = parseInt ( _newValueSplit [1]) > year
            const _month = new Date().getMonth() + 1
            const _nowMonth = parseInt ( _newValueSplit [0] )
            const _monthL =  _nowMonth < _month
            if ( ! _temp || _monthL && ! _temp1 ) {
                this.cardNumberDate_success ( false )
                this.cardNumberDate_error ( true )
                return
            }
            this.cardNumberDate_success ( true )
            this.cardNumberDate_error ( false )
            this.paymentUserInformationButton ( this.cardNumber1_success() && this.cardNumber1Cvc_success() && this.cardNumberDate_success())
        }

        public tileClick = (data) => {
            var self = this;
            self.keyPairLengthSelect(data);
            return true;
        };


        public logout = () => {
            $.removeCookie('Vpn.Email')
            window.location.href="/"
        }       
    } 
}
var viewLayout = new view_layout.view ()
ko.applyBindings ( viewLayout, document.getElementById ("body"))
