if(staticContextPath){
    var path = contextPath;
    var runtimePath = runtimePath;
}else{
    var pathName = document.location.pathname;
    var index = pathName.substr(1).indexOf("/");
    var contextPath = pathName.substr(0, index + 1);
    //配置runtime的项目路径
    var runtimePath = "/obpm";
    //这里配置项目路径
    var myContextPath = "";
    if (myContextPath) {
        contextPath = myContextPath;
    }
    var path = contextPath;
}
var Api = {
	loginWithCiphertext2: function (data) {
		return $.ajax({
			url: path + "/runtime/login/loginWithCiphertext2",
            type: 'post',
            async: false,
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(data)
		})
	},
    checkin: function (data) {
		return $.ajax({
			url: path + "/runtime/login/checkin",
            type: 'post',
            async: false,
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(data)
		})
	},
    signin: function (data) {
		return $.ajax({
			url: path + "/runtime/login/signin",
            type: 'post',
            async: false,
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(data)
		})
	},
    autoLogin :function(){
	    return $.ajax({
            url:  path + "/runtime/login/autologin",
            type: 'post',
            async: false,
            dataType: 'json',
            contentType: 'application/json'
        })
    },
    getDomainList : function () {
        return $.ajax({
            url: path +"/runtime/login/getDomainList",
            type: 'post',
            async: false,
            dataType: 'json',
            contentType: 'application/json'
        })
    },
    changeCheckcodeImg : function () {
        return $.ajax({
            url:  path +"/runtime/login/changeCheckcodeImg",
            type: 'post',
            async: false,
            dataType: 'json',
            contentType: 'application/json'
        })
    },
    getMultiLangWordList : function (data) {
        return $.ajax({
            url: path + "/runtime/login/getMultiLangWordList",
            type: 'post',
            async: false,
            dataType: 'json',
			data: JSON.stringify(data),
            contentType: 'application/json'
        })
    }
};

function GetQueryString(name) {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);//search,查询？后面的参数，并匹配正则
    if(r!=null)return  unescape(r[2]); return null;
}
function QueryString(){
    var query = window.location.search.substring();
    if(query.indexOf("?")>=0){
        if(query.split("?")[1].indexOf("kms")>=0){
            return "kms";
        }else if(query.split("?")[1].indexOf("good")>=0){
            return "good";
        }else if(query.split("?")[1].indexOf("vue")>=0){
            return "vue";
        }
    }
    return (undefined);
}

function getExplorer() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    //判断是否IE<11浏览器
    var isIE11 = userAgent.indexOf('Mozilla/5.0') > -1 ;
    if (!isIE11) {
        return "noIE11";
    }
}
var timeoutNum;
function getTimeOutNum(){
    var $container = $('.indexLogin')
    var telephone = $container.find("#telephone").val();
    var domainName = $container.find("#domainList").val();
    if(!telephone){
        //alert("请填写手机号")
		$container.find(".error-tip").text("请填写手机号");
		$container.find(".error-tip").show();
		$('.errorMsg').text("请填写手机号");
		$('#errorCon').show();
		return;
    }

    $.ajax({
        url: path + "/runtime/login/smsauth?telephone="+telephone+"&domainName="+domainName,
        type:"get",
        dataType:"json",
        async:false,
        success: function(data){
            if(data.resultCode == 1){
                $("#sendCode").attr("disabled",true).css("pointer-events","none");
                timeoutNum = data.timeout;
                getNewTimeoutNum(1);
            }else{
                //alert(data.msg)
				$container.find(".error-tip").text(data.msg);
				$container.find(".error-tip").show();
				$('.errorMsg').text(data.msg);
				$('#errorCon').show();
            }

        }
    });
}
var interval;
function getNewTimeoutNum(i){
    //定时器每秒减1
	if(interval) clearInterval(interval);
    interval = setInterval(function(){
        timeoutNum = timeoutNum -i;
        console.log(timeoutNum);
        if (timeoutNum == 0) {
            document.getElementById("sendCode").innerHTML = "<span style='color:#009fe5;'>重发短信</span>";
            $("#sendCode").attr("disabled",false).css("pointer-events","auto");
            clearInterval(interval)
        } else {
            document.getElementById("sendCode").innerHTML = "&nbsp;"+timeoutNum+"&nbsp;秒后重发";
        }
        console.log("timeoutNum="+timeoutNum)

    }, 1000);
}
//重发短信
function sendCode(){
    getTimeOutNum();
}
function decorator() {
    var debug = GetQueryString("debug");
    var path;
    var explorer = getExplorer();
    if (explorer != null && explorer.toString().length > 0){
        if (debug != null){
            window.location.href = path + "/portal/share/security/login.jsp?debug=true"
        } else {
            window.location.href = path + "/portal/share/security/login.jsp"
        }
    }
    var Login = {
    	config: {},
        container: null,
        init : function (container) {
            Login.container = container;
            Login._renderView();
        },
		_renderView : function () {
            var $container = $(Login.container);
            // Api.getMultiLangWordList().done(function (response) {
            //     result = response;
            //     console.log(result)
            // });

            //判断自动登陆
            Api.autoLogin().done(function (response) {
                result = response;
                if (result.resultCode == 1){
                    window.location.href = path + result.url;
                }
            });

            Api.getMultiLangWordList({"language": "CN"}).done(function(response) {
                console.log("初始化多语言");
            });

            //获取企业域
            Api.getDomainList().done(function(response) {
                result = response;
                if(result.resultCode == 0) {
                    alert(result.msg);
                } else {
                    var ipos,ListStr1,ListStr2;
                    result= result.result;
                    var list = result.domainList;
                    //判断是否上传了背景图片
                    if(result.loginBackground){
                        var url = signonPath + result.loginBackground;
                        $(".bg").find("img").attr("src",url);
                    }
                    var $ul = $("#domain");
                    if(list.length>1){
                        var isShowWX = false;
                        var isShowDD = false;
                        var dingdingDefault = false;
                        for(var i=0;i<list.length;i++){
                            ipos = list[i].indexOf("@");
                            ListStr1=list[i].substring(0,ipos); //取前部分
                            ListStr2=list[i].substring(ipos,list[i].length).replace(/[^0-9]/ig,"");//取后部分
                            if(ListStr2 == 1){
                                isShowWX = true;
                            }else if(ListStr2 == 2){
                                isShowDD = true;
                                if(!dingdingDefault){
                                    $('.login-fill>input[name=defaultDDType]').val(ListStr2);
                                    $('.login-fill>input[name=defaultDDName]').val(ListStr1);
                                    dingdingDefault = true;
                                }
                            }else if(ListStr2 == 3){
                                isShowWX = true;
                                isShowDD = true;
                                if(!dingdingDefault){
                                    $('.login-fill>input[name=defaultDDType]').val(ListStr2);
                                    $('.login-fill>input[name=defaultDDName]').val(ListStr1);
                                    dingdingDefault = true;
                                }
                            }
                            if(ListStr2 != 0){
                                var $li = $('<li class="option-item" value='+ListStr2+'>'+ListStr1+'</li>');
                                $ul.append($li);
                            }
                        }
						//判断是否超过11个企业域，超过定高度，出现滚动条,li高度32
                        var ulHeight = list.length*32;
                        if(ulHeight>250){
                            $ul.css("height","250px");
                        }
                        $('.login-fill>input[name=isShowWX]').val(isShowWX);
                        $('.login-fill>input[name=isShowDD]').val(isShowDD);
                        if(!isShowWX && !isShowDD){
                            $('.wx').hide();
                            $('.wx_hui').show();
                            $('.dd').hide();
                            $('.dd_hui').show();
                        }else if(isShowWX && isShowDD){
                            $('.wx').show();
                            $('.wx_hui').hide();
                            $('.dd').show();
                            $('.dd_hui').hide();
                        }else if(isShowDD){
                            $('.wx').hide();
                            $('.wx_hui').show();
                            $('.dd').show();
                            $('.dd_hui').hide();
                        }else if(isShowWX){
                            $('.wx').show();
                            $('.wx_hui').hide();
                            $('.dd').hide();
                            $('.dd_hui').show();
                        }
                        $(".login-form-group").hide();
                        $(".domainLi").show();
                    } else {
                        ipos = list[0].indexOf("@");
                        ListStr1=list[0].substring(0,ipos); //取前部分
                        ListStr2=list[0].substring(ipos,list[0].length).replace(/[^0-9]/ig,"");//取后部分
                        $("#configType").val(ListStr2);
                        $("#domainList").val(ListStr1);
                        if(ListStr2==0){
                            $('.wx').hide();
                            $('.wx_hui').show();
                            $('.dd').hide();
                            $('.dd_hui').show();
                        }else if(ListStr2==1){
                            $('.wx').show();
                            $('.wx_hui').hide();
                            $('.dd').hide();
                            $('.dd_hui').show();
                        }else if(ListStr2==2){
                            $('.wx').hide();
                            $('.wx_hui').show();
                            $('.dd').show();
                            $('.dd_hui').hide();
                        }else{
                            $('.wx').show();
                            $('.wx_hui').hide();
                            $('.dd').show();
                            $('.dd_hui').hide();
                        }
                    }
                }
            });
            this._bindEvent();
		},
        _bindEvent : function() {
            var $container = $(this.container);
            var that = this;
            // $container.on('change', '#pwd', function(e) {
            //     processPassword();
            // });
            //登录
            _loginIn = function (){
                var userName = $container.find("#userName").val();
                processPassword();
                var pwd = $container.find("#pwdhidden").val();
                //勾选了下次自动登录存储进缓存
                var oldpwd = $container.find("#pwd").val();
                if($("#remember").is(":checked")){
                    var obj = {
                        userName : userName,
                        userPwd : oldpwd,
                    }
                    if(!localStorage.getItem("userMessage")){
                        obj.newTime = new Date().getTime();
                    }else{
                        obj.newTime = JSON.parse(localStorage.getItem("userMessage"))[0].newTime;
                    }
                    var arr = [];
                    arr.push(obj)
                    localStorage.setItem("userMessage",JSON.stringify(arr));
                }else{
                    localStorage.removeItem("userMessage");
                }
                var isPC = true;
                if(window.pathName && window.pathName.indexOf("mobilelogin.html")>=0){
                    isPC = false;
                }
                var remember = $container.find("#remember").prop('checked') ? "1" : "0";
                var debug = GetQueryString("debug") != null ? GetQueryString("debug") : "false";
                var domainName = $container.find("#domainList").val();
                var checkcode = $container.find("#checkcode").val();
                var language = $container.find(".select-head-cont").attr("data-lang");
                var url;
                if(staticContextPath){
                    url = null;
                }else{
                   url = isPC ? runtimePath + "/" : runtimePath;
                }
                var loginIn = $container.find(".btnOk");
                var loginInwrd = loginIn.text();
                console.log(loginInwrd)
                if(loginInwrd != "登录"){
                    var loginInnewwrod = loginIn.text() +" ing...";
                }else{
                    var loginInnewwrod = loginIn.text() +"中...";
                }
				if(loginInnewwrod == "登录中... ing..."){
					return false;
				}
                var skin = QueryString();
                //判断是不是手机短信登录
                if($(".changeLogin").length>0 && !$(".changeLogin").is(":hidden")){
                    var smsCheckCode = $("#vCode").val();
                    var telephone = $container.find("#telephone").val();
                    var domainName = $('.indexLogin').find("#domainList").val();
                    if(smsCheckCode == ""){
                        loginIn.text(loginInwrd);
                        //alert("验证码不能为空");
						$container.find(".error-tip").text("验证码不能为空");
						$container.find(".error-tip").show();
						$('.errorMsg').text("验证码不能为空");
						$('#errorCon').show();
						return;
                    }
                    var data = {
                        telephone : telephone,
                        domainName : domainName,
                        smsCheckCode : smsCheckCode,
                        path : path,
                        url : url
                    }
                    $.ajax({
                        url: contextPath + "/runtime/login/loginSMS",
                        type: "post",
                        data: JSON.stringify(data),
                        datatype: "json",
                        contentType: 'application/json',
                        success: function (data) {
                            if(data.resultCode == 1){
								loginIn.text(loginInwrd);
                                var url;
                                if(staticContextPath){
                                    url = staticContextPath + data.returnUrl;
                                }else{
                                    url = "../obpm"
                                }
								window.location.href = url;
                            }else{
                                //alert(data.msg);
								$container.find(".error-tip").text(data.msg);
								$container.find(".error-tip").show();
								$('.errorMsg').text(data.msg);
								$('#errorCon').show();
								return;
                            }
                        }
                    });
                }else {
                    Api.checkin({
                        username : userName,
                        password : pwd,
                        checkcode : checkcode,
                    }).done(function (response) {
                        var result = response;
                        if(result.resultCode == 0) {
                            $container.find(".error-tip").text(result.msg);
                            $container.find(".error-tip").show();
                            $('.errorMsg').text(result.msg);
                            $('#errorCon').show();
                            if(result.checkcodeImg){
                                $container.find(".verification").show();
								$(".login-fill").css("height","470px");
                                $container.find(".code img").attr("src",result.checkcodeImg)
                            }
                            loginIn.text(loginInwrd);
                        }else{
                            loginIn.text(loginInwrd);
                            if(result.domains.length == 1){
                                Api.signin({
                                    userDomainName : userName + "@@" + result.domains[0].name,
                                    remember : remember,
                                    url: url,
                                    checkInToken : result.checkInToken
                                }).done(function (response) {
                                    var jumptoUrl = "";
                                    if(skin == "kms"){
                                        jumptoUrl = staticContextPath + "/kms/kmspc/index.html"
                                    }else if(skin == "good"){
                                        jumptoUrl = staticContextPath + (staticContextPath ? "" : runtimePath) + "/portal/good/index.html";
                                    }else if(skin == "vue"){
                                        jumptoUrl = staticContextPath + (staticContextPath ? "" : runtimePath) + "/portal/vue/index.html";
                                    }else{
                                        jumptoUrl = staticContextPath + response.returnUrl;
                                    }
                                    window.location.href = jumptoUrl;
                                })
                            }else{
                                var type = "pclogin";
                                // if(window.pathName && window.pathName.indexOf("mobilelogin.html")>=0){//window.pathName 5.0为undefined
                                //     type = "mobilelogin";
                                // }
								if(window.location.href && window.location.href.indexOf("mobilelogin.html")>=0){
                                    type = "mobilelogin";
                                }
                                window.location.href = "./domain.html?url=" + url + "&userName=" + userName + "&remember=" + remember + "&checkInToken="+ result.checkInToken + "&type=" + type;
                            }
                            // window.location.href = path + result.returnUrl;
                        }
                    })
                }
            };
            $container.on('click', '.btnOk', function(e) {
                _loginIn();
            });
            $(document).keydown(function(e){
                if(e.keyCode == "13"){
                    $container.find("#pwd").blur();
                    _loginIn();
                }
            });
            //企业域下拉
            // $(".drop-down").click(function () {
            //     $("#domain").show();
            // });
            // $("#domainList").click(function () {
            //     $("#domain").show();
            //     event.stopPropagation();
            // });
            //$(document).click(function (e) {
            //    if ($(e.target).parents().next().hasClass("domain")){                   
            //   } else {
            //    $(".domain").hide();
            //    if($("#domainList").val()==""){
            //        $('.wx').hide();
            //        $('.wx_hui').show();
            //        $('.dd').hide();
            //        $('.dd_hui').show();
            //    }
            //   }
            //});            
            $container.find("#domain li").click(function () {
                var word = $(this).text();
                var value = $(this).val();      
                if(!$(".weixinLogin").is(":hidden")){
                    $(".weixinLogin").find("#domainList").val(word);
                    $(".weixinLogin").find("#configType").val(value);
                    $(".weixinLogin").find("#domain").hide();
                    $(".weixinLogin").find("#domainList").next().next().addClass("del-tran");
                    //$(this).parent().parent().find(".mu-text-field-label").addClass("del-tran");
                }else if(!$(".dingdingLogin").is(":hidden")){
                    $(".dingdingLogin").find("#domainList").val(word);
                    $(".dingdingLogin").find("#configType").val(value);
                    $(".dingdingLogin").find("#domain").hide();
                    $(".dingdingLogin").find("#domainList").next().next().addClass("del-tran");
                    //$(this).parent().parent().find(".mu-text-field-label").addClass("del-tran");
                }else{
                    $(".indexLogin").find("#domainList").val(word);
                    $(".indexLogin").find("#configType").val(value);
                    $(".indexLogin").find("#domain").hide();
                    $(".indexLogin").find("#domainList").next().next().addClass("del-tran"); 
                }                                         
                if(value==0){
                    $('.wx').hide();
                    $('.wx_hui').show();
                    $('.dd').hide();
                    $('.dd_hui').show();
                }else if(value==1){
                    $('.wx').show();
                    $('.wx_hui').hide();
                    $('.dd').hide();
                    $('.dd_hui').show();
                }else if(value==2){
                    $('.wx').hide();
                    $('.wx_hui').show();
                    $('.dd').show();
                    $('.dd_hui').hide();
                }else{
                    $('.wx').show();
                    $('.wx_hui').hide();
                    $('.dd').show();
                    $('.dd_hui').hide();
                }
                if(!$(".weixinLogin").is(":hidden")) $('.wx').click();
            });
			//多语言处理
            $container.on("click", ".option-item", function () {
                var language = $container.find(".select-head-cont").attr("data-lang");
                Api.getMultiLangWordList({
                    language:language
                }).then(function (response) {
                    var result = response;
                    var domains = result.multiLangWordList.domains;
                    var copyright = result.multiLangWordList.frontPageLoginCopyright;
                    var login = result.multiLangWordList.login;
                    var account = result.multiLangWordList.pageLoginAccount;
                    var password = result.multiLangWordList.pageLoginPassword;
                    var label = result.multiLangWordList.pageLoginRememberLabel;
 
                    var telephone= result.multiLangWordList.mobile; //手机号
                    var code=result.multiLangWordList.code;         //验证码
                    var loginway=result.multiLangWordList.loginway; //账号密码登录
                    var getCode=result.multiLangWordList.getCode;   //获取验证码

                    $container.find(".telephone-word").text(telephone);
                    $container.find(".vCode-word").text(code);
                    $container.find(".changeLogin").text(loginway);
                    $container.find(".sendCode").text(getCode);
                   
                    $container.find(".login-operation h3").text(login);
                    $container.find(".domainword").text(domains);
                    $container.find(".username-word").text(account);
                    $container.find(".pwd-word").text(password);
                    $container.find(".obpm-checkboxLogin").text(label);
                    $container.find(".domainword").text(domains);
                    $container.find(".copyright").text(copyright);
                    $container.find(".btnOk").text(login);

                })
            });
            //改变验证码
            $container.on("click", ".code", function () {
                Api.changeCheckcodeImg().done(function(response) {
                    var result = response.checkcode;
                    $container.find(".code img").attr("src",result)
                })
            });
        }

    }

    return {
    	init: Login.init
	}
}


//企业域验证
// function showDomainTips(obj,tips) {
// 	var tipsArea = document.getElementById("tipsdiv_Domain");
// 	var tipscontain =document.getElementById("easyDomaintip-text");
// 	tipsArea.style.display="block";
// 	tipscontain.innerHTML = tips;
// 	var style = "font-size:12px; color:blue;";
// }
// function disableDomainTips(obj) {
// 	var tipsArea = document.getElementById("tipsdiv_Domain");
// 	var tipscontain =document.getElementById("easyDomaintip-text");
// 	tipsArea.style.display="none";
// 	tipscontain.innerHTML = "&nbsp;";
// }
//验证码验证
// function showCodeTips(obj,tips) {
// 	var tipsArea = document.getElementById("tipsdiv_code");
// 	var tipscontain =document.getElementById("easyCodetip-text");
// 	tipsArea.style.display="block";
// 	tipscontain.innerHTML = tips;
// 	var style = "font-size:12px; color:blue;";
// }
// function disableCodeTips(obj) {
// 	var tipsArea = document.getElementById("tipsdiv_code");
// 	var tipscontain =document.getElementById("easyCodetip-text");
// 	tipsArea.style.display="none";
// 	tipscontain.innerHTML = "&nbsp;";
// }

// function changeLanguage(){
// 	var obj = document.getElementById("debug");
// 	var showCode = document.getElementsByName("_showCode")[0].value;
// 	//切换皮肤不用传输密码,去除密码元素
// 	/*document.getElementsByName("password")[0].value = "";*/
// 	var password=document.getElementsByName("password")[0];
// 	password.parentNode.removeChild(password);
// 	var url = contextPath+'/core/multilanguage/change.action';
// 	if (obj != null && obj.value != null)
// 		url = url + "?debug="+obj.value;
//
// 	if(showCode){
// 		if(url.indexOf("?")>0){
// 			url = url + "&showCode=" + showCode;
// 		}else{
// 			url = url + "?showCode=" + showCode;
// 		}
// 	}
// 	document.forms[0].action = url;
// 	document.forms[0].submit();
// }


// var timeout = "";//企业域下拉列表中使用
// function showDomain(){
// 	document.getElementById('domain').style.display="block";
// 	var domainHeight = document.getElementById("domain").offsetHeight;
// 	if(domainHeight>350){
// 		document.getElementById("domain").style.height=350+"px";
// 	}
// }
// function hideDomain(){
// 	timeout = window.setTimeout("document.getElementById('domain').style.display='none'",300);
// }
// function hiddendoMainOver(){
// 	window.clearTimeout(timeout);
// }
// function selectDomain(obj){
// 	var option = document.getElementsByName('domainName');
// 	var domain=obj.innerHTML;
// 	option[0].value=domain;
// 	document.getElementById('domain').style.display='none';
// 	$(obj).parents("#domain").siblings(".selectdoMain").find("div").css("display","none");
// }


// function focusOn(obj) {
// 	obj.select();
// 	obj.focus();
// }
// window.onload=function(){
//     //要初始化的东西
// 	//changeWidth();
// }
//
// window.onresize = function() {
// 	//reSize();
// 	changeWidth();
//
// };
//
// function reSize(){
// 	var obj = document.getElementById("loginform");
// 	var contentObj = document.getElementById("content");
// 	var browserHeight = document.documentElement.offsetHeight;
// 	var browserWidth = document.documentElement.offsetWidth;
// 	if(browserWidth<650){
// 		document.getElementById("bodyid").style.overflow="auto";
// 	}else{
// 		document.getElementById("bodyid").style.overflow="hidden";
// 	}
// 	if(browserHeight<450){
// 		document.getElementById("bodyid").style.overflow="auto";
// 	}
// 	if (obj) {
// 		obj.style.height = browserHeight - 30 + "px";
// 		obj.style.width = browserWidth -3+ "px";
// 	}
// }

/**
 * 加密密码
 * @returns
 */
function processPassword(){
	var b = new Base64();
	var pw = document.getElementById('pwd');
	if(!pw.value){
		return;
	}
    var obj = {
        pwd : pw.value
    }
    var newPw = JSON.parse(JSON.stringify(obj)).pwd
	var str = b.encode(newPw);
	if(str.length>2){
		var lp = str.substr(0,2);
		var rp = str.substr(2,str.length);
        document.getElementById('pwdhidden').value = rp+lp;
	}
}
//
// //点击之后，显示“登录中...”
// function login_ing(obj){
// 	processPassword();
// 	var btn = document.getElementById("tijiao");
// 	btn.value = btn.value + "ing...";
// 	btn.onclick = null;
// 	document.forms[0].action = contextPath+"/runtime/login/loginWithCiphertext.action";
// 	document.forms[0].submit();
// }
//
// //点击之后，显示“登录中...”
// function login_dialog_ing(obj){
// 	processPassword();
// 	var btn = document.getElementById("tijiao");
// 	btn.value = btn.value + "ing...";
// 	btn.onclick = null;
// 	document.forms[0].action = contextPath+"/runtime/login/loginInDialog.action";
// 	document.forms[0].submit();
// }
//登陆内容的宽度不时改变
// function changeWidth(){
// 	var loginWidth=0;
// 	var num = document.getElementById("loginInfo").getElementsByTagName("li").length;
// 	var li = document.getElementById("loginInfo").getElementsByTagName("li");
// 	for(var i=0;i<num;i++){
// 		loginWidth += parseInt(li[i].offsetWidth);
// 	}
// 	// document.getElementById("login-box").style.width=loginWidth+30+"px";
// 	// document.getElementById("login-box").style.marginTop = 0+"px";
// }


function Base64() {

	// private property
	_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

	// public method for encoding
	this.encode = function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = _utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
			_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
			_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		return output;
	}

	// public method for decoding
	this.decode = function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		while (i < input.length) {
			enc1 = _keyStr.indexOf(input.charAt(i++));
			enc2 = _keyStr.indexOf(input.charAt(i++));
			enc3 = _keyStr.indexOf(input.charAt(i++));
			enc4 = _keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = _utf8_decode(output);
		return output;
	}

	// private method for UTF-8 encoding
	_utf8_encode = function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}
		return utftext;
	}

	// private method for UTF-8 decoding
	_utf8_decode = function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}




