PKToonWeb = {
    Name: '拼卡通',
    WebSite: 'http://www.pktoon.cn',
    Request:null,
    PreDiv: null,
    TimeOut:null,
    /*容器*/
    Container:new Hash,
    BrowserVersion:function(){
        var ver = [];
        var user_agent = navigator.userAgent.toLowerCase();
        var ie_version = user_agent.match(/msie ([\d.]+)/);
        if(ie_version != null){
            ver[0] = ie_version[0];
            ver[1] = ie_version[1];
            return ver;
        }
        var firefox_version = user_agent.match(/firefox\/([\d.]+)/);
        if(firefox_version != null){
            ver[0] = firefox_version[0];
            ver[1] = firefox_version[1];
            return ver;
        }
        return [0,0];
    }
};
PKUtil = {
    //显示提示信息
    showTip:function(obj,tip_text,p_left,p_top,callback){
        if(PKToonWeb.PreDiv != null){
            $(PKToonWeb.PreDiv).hide();
        }
        if (PKToonWeb.TimeOut != null)
        {
            clearTimeout(PKToonWeb.TimeOut);
        }
        var tipDiv = document.createElement("div");
        tipDiv.classname = 'tip';
        var div_id = "div_" + Math.random();
        tipDiv.id = div_id;
        tipDiv.style.width = "107px";
        tipDiv.style.height = "31px";
        tipDiv.style.textAlign = "center";
        tipDiv.style.color = '#999';
        var image_path = PKToonWeb.Container.get("theme_path");
        if(image_path == undefined || image_path == null){
            image_path = "/images";
            tipDiv.style.color = '#000';
        }
        tipDiv.style.backgroundImage = 'url('+image_path+'/BACKGROUND-tips.gif)';
        tipDiv.style.paddingTop="10px";
        tipDiv.style.backgroundRepeat = 'no-repeat';
        tipDiv.style.position = 'absolute';
        tipDiv.innerHTML = tip_text;
        document.body.appendChild(tipDiv);
        PKToonWeb.PreDiv = tipDiv;
        $(div_id).style.top = $(obj).cumulativeOffset()[1] - p_top +"px";
        $(div_id).style.left= $(obj).cumulativeOffset()[0] - p_left +"px";
        $(div_id).show();
        if(!callback.blank()){
            PKToonWeb.TimeOut = setTimeout(callback,1000);
        }
    },
    //消除提示框
    clearTip:function(){
        new Effect.BlindUp(PKToonWeb.PreDiv.id,{
            afterFinish:function(effect){
               $(PKToonWeb.PreDiv).remove();
            }
        });
    },
    //取回资源数据
    retrievePage:function(resource, receiver_id,page_num){
        var retrieve = function(url,r_id){
            try{
                PKToonWeb.Container.set(url, r_id);
                PKToonWeb.Request = new Ajax.Request(url,
                {
                    method: "get",
                    onSuccess: PKUtil.retrievePageResult,
                    onFailure: function(rsp){
                        PKToonWeb.Container.unset(rsp.request.url);
                    }
                });
            }catch (e){
                PKToonWeb.Container.unset(url);
            }
        };
        if(page_num == undefined || page_num == null){
            return retrieve(resource, receiver_id);
        }else{
            if(page_num.blank())
                return ;
            try{
                var pn = parseInt(page_num);
                var gpt = parseInt($('gen_page_total').value);
                if(pn > gpt){
                    $("page_num_input").value = "";
                    return;
                }
            }catch(e){
                $("page_num_input").value = "";
                return;
            }
            var url = resource.replace("<page_num>", page_num);
            retrieve(url, receiver_id);
        }
    },
    loadPage:function(resource, receiver_id,form_id,page_num){
        var load = function(url, r_id){
            try{
                PKToonWeb.Container.set(url, r_id);
                PKToonWeb.Request = new Ajax.Request(url,
                {
                    method: "post",
                    postBody:Form.serialize($(form_id)),
                    onSuccess: PKUtil.retrievePageResult,
                    onFailure: function(rsp){
                        PKToonWeb.Container.unset(rsp.request.url);
                    }
                });
            }catch (e){
                PKToonWeb.Container.unset(url);
            }
        };
        if(page_num == undefined || page_num == null){
            return load(resource, receiver_id);
        }else{
            if(page_num.blank())
                return ;
            try{
                var pn = parseInt(page_num);
                var gpt = parseInt($('gen_page_total').value);
                if(pn > gpt){
                    $("page_num_input").value = "";
                    return;
                }
            }catch(e){
                $("page_num_input").value = "";
                return;
            }
            var url = resource.replace("<page_num>", page_num);
            load(url, receiver_id);
        }
    },
    //取回的数据结果
    retrievePageResult:function(rsp){
        try{
            var receiver_id = PKToonWeb.Container.get(rsp.request.url);
            PKToonWeb.Container.unset(rsp.request.url);
            $(receiver_id).innerHTML = "";
            Element.insert(receiver_id, rsp.responseText);
            var callback = PKToonWeb.Container.get("card");//callback_after_retrieve_data
            if(callback != undefined && callback != null && !callback.blank()){
                PKToonWeb.Container.unset("card");
                eval(callback);
            }
        }catch (ex) {
        }
    },
    //清除提示框后执行回调方法
    clearTipBeforeLoad:function(callback){
        new Effect.BlindUp(PKToonWeb.PreDiv.id,{
            afterFinish:function(effect){
            	var is_stop = PKToonWeb.Container.get("stopRequest");
            	if(is_stop == undefined || is_stop == null || is_stop == '')
                	eval(callback);
                PKToonWeb.Container.unset("stopRequest");
                $(PKToonWeb.PreDiv).remove();
            }
        });
    },
    //加载Javascript
    loadJavascript:function(file){
        if(document.getElementsByTagName){
            var doc = document.getElementsByTagName('head')[0];
            var js = document.createElement("script");
            js.setAttribute("type", "text/javascript");
            var date = new Date().getTime().toString();
            js.setAttribute("src", file + "?" + date);
            doc.appendChild(js);
        }
    },
    //验证令牌
    authenticityToken:function() {
        var encodeAuthen = function(token){
            return encodeURIComponent($F(token)) ;
        };
        return 'authenticity_token=' + encodeAuthen(document.getElementsByName('authenticity_token')[0]);
    },
    //显示浮动层
    showModal:function(resource, width, height, loadingString,optional){
        var dlg = $('popup_dialog');
        var bg = $('popup_bg');
        try {
            var docWidth = document.viewport.getWidth();
            var docHeight = document.viewport.getHeight();
            dlg.style.display    = '';
            var l = docWidth > width ? Math.floor((docWidth - width) / 2) : 0;
            var t = docHeight > height ? Math.floor((docHeight - height) / 2) : 0;
            if(Prototype.Browser.IE){
            	
                if (PKToonWeb.BrowserVersion()[1] < 7){
                	
                    l = document.documentElement.scrollLeft + l;
                    t = document.documentElement.scrollTop + t;
                }
            }
            dlg.style.left = l + 'px';
            dlg.style.top = t + 'px';
            dlg.style.width	= width + 'px';
            dlg.style.height = height + 'px';
            if(optional != undefined && optional != null && optional != ''){
                if(optional.Opacity != undefined)
                    bg.setOpacity(optional.Opacity);
                if(optional.backgroundColor != undefined)
                    bg.style.backgroundColor = optional.backgroundColor;
            }else{
                bg.setOpacity(0.2);
                bg.style.backgroundColor = "#000";
            }
            bg.style.display        = '';
            bg.style.height        =docHeight + document.documentElement.scrollTop + 'px';// document.body.clientHeight + document.documentElement.scrollTop + 'px';
            bg.style.width        = document.body.clientWidth + 'px';
        }catch(e){}
		if(loadingString.blank()){
			$('popup_content').innerHTML = '<div style="width:242px;height:52px;padding-top:10px;background:url(/images/loading_bg.gif) no-repeat;text-align:center"><div style="font-size:12px;color:#000">页面加载中请稍候...</div><img src="/images/loading.gif" style="margin-top:5px" /></div>';	
		}else{
			$('popup_content').innerHTML = loadingString;	
		}
        new Ajax.Request(resource,
        {
            method: "get",
            onSuccess: function(rsp){
                if (rsp.status / 100 == 2){
                 //   $('popup_content').innerHTML = rsp.responseText;
                    $('popup_content').innerHTML = "";
                    Element.insert('popup_content', rsp.responseText);
                    var do_after_loaded = PKToonWeb.Container.get("casm"); //callback_after_show_modal
                    if(do_after_loaded !=undefined && do_after_loaded != null && !do_after_loaded.blank()){
                        PKToonWeb.Container.unset("casm");
                        eval(do_after_loaded);
                    }
                }else{
                    PKUtil.closeModal();
                }
            },
            onFailure: function(rsp){
                PKUtil.closeModal();
            }
        });
    },
    //关闭浮动层
    closeModal:function(){
        $('popup_content').innerHTML = "";
        $('popup_dialog').style.display    = 'none';
        $('popup_bg').style.display        = 'none';
    },
    //获取验证码
    getVerifyImage:function(input_name,width_per_char,img_height,pointsize){
        if(input_name.blank()){
            return false;
        }
        var width = width_per_char || 32;
        var height = img_height || 50;
        var ps = pointsize || 40;
        $(input_name + "_image").src = "/user_checker/code_image/" + input_name + "/" + width + "/" + height + "/" + ps + "?" + Math.random();
        $(input_name).value = "";
        return false;
    },
    //对字符串进行UTF8编码
    urlEncode:function(value){
        return encodeURIComponent(value);
    },
    //定时执行指定的方法，以秒作为单位
    schedule:function(method,second){
        method.apply();
        return window.setInterval(method,second * 1000);
    },
    //判断输入框内容是否超过指定数目
    checkCounter:function(counter,maxCharacters){
        var contents = counter.value.split("");
        var strContent = "";//有效内容
        var all_Num = 0;
        var oldContent = PKToonWeb.Container.get("count_content");
        for (var i = 0; i < contents.length; i++){
            if(all_Num > maxCharacters){
                alert("最多只能输入" + maxCharacters + "个字符");
                if(oldContent != null){
                    counter.value = PKToonWeb.Container.get("count_content");
                }else{
                    counter.value = strContent;
                }
                all_Num = PKUtil.count(counter.value.split(""));
                return (maxCharacters - all_Num) > 0 ? (maxCharacters - all_Num):0;
            }
            var strChar = contents[i];
            if (strChar == '\n'){
                all_Num += 2;
            }else{
                if(!strChar.match(/[^\u4E00-\u9FA5]/g) || !strChar.match(/[^\uFF00-\uFFFF]/g)){
                    all_Num += 2;
                }else{
                    all_Num ++;
                }
                strContent += strChar;
            }
        }
        PKToonWeb.Container.set("count_content",strContent);
        return (maxCharacters - all_Num) > 0 ? (maxCharacters - all_Num):0;
    },
    //计算给定字符串中的字符数目
    count:function(contents){
        var all_Num = 0;
        for(var i = 0; i < contents.length; i++){
            var strChar = contents[i];
            if (strChar == '\n'){
                all_Num += 2;
            }else{
                if(!strChar.match(/[^\u4E00-\u9FA5]/g) || !strChar.match(/[^\uFF00-\uFFFF]/g)){
                    all_Num += 2;
                }else{
                    all_Num ++;
                }
            }
        }
        return all_Num;
    },
    //设置cookie
    setCookie:function(s){
        var index = 0;
        index = s.indexOf(", ztC", index);
        if (index == -1) return;
        document.cookie = s.substring(index + 2);
        document.cookie = s.substring(0, index);
    },
    //检验帐号名称有效性
    validateAccountName:function(accountName){
        return /^[\w,@,\.,-]{4,32}$/.test(accountName);
    },
    //检验密码有效性
    validatePassword:function(password){
        return /^.{6,20}$/.test(password);
    },
    validateEmail:function(email){
        return /^[\w,\.,-]+@\w+(.\w+)+$/.test(email);
    },
    validateVerifyCode:function(verifyCode){
        return /^\w{4}$/.test(verifyCode);
    },
    validatePhoneNumber:function(number){
        return /^\d{6,15}$/.test(number);
    },
    validateQQ:function(qq){
        return /^\d{4,11}$/.test(qq);
    },
    validateName:function(name){
        return /^.+$/.test(name);
    },
    validateDate:function(date){
        return /^(\d{4})-(\d{1,2})-(\d{1,2})$/.test(date);
    },
    clearNeedSignAction:function(){
        new Ajax.Request("/user/clear_need_sign_action", {
            method: "get",
            onSuccess: function(rsp) {},
            onFailure: function(rsp) {}
        });
    },
    // 散列用户密码
    passwordDigest : function(key, password) {
        return PKUtil.Crypto.hexHmacMd5(key, PKUtil.Crypto.hexMd5(password));
    },
    getEvent:function(){
        if(document.all)
            return window.event;
        var func=PKUtil.getEvent.caller;
        while(func!=null){
            var arg0=func.arguments[0];
            if(arg0){
                if((arg0.constructor==Event || arg0.constructor ==MouseEvent)
                    || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation)){
                    return arg0;
                }
            }
            func=func.caller;
        }
        return null;
    },
    checkSubmit:function(element){
        var keynum;
        if(window.event) { // IE
            keynum = window.event.keyCode;
        }
        else { // Netscape/Firefox/Opera
            var evt=PKUtil.getEvent();
            if (evt.which) {
                keynum = evt.which;
            }
        }
        if (keynum == 13) {
            var btn = $(element);
            if (btn) {
                btn.focus();
                btn.click();
                return false;
            }
        }
        return true;
    },
    isClientInstalled:function(){
        try{
            var obj = new ActiveXObject("PKToonLib.WebAdapter");
            return obj != null;
        }catch(ex){
            return false;
        }
    },
    isClientRunning:function(){
        try{
            var obj = new ActiveXObject("PKToonLib.WebAdapter");
            return obj.IsClientRunning();
        }catch(ex){
            return false;
        }
    },
    getClientVersion:function(){
        try{
            var obj = new ActiveXObject("PKToonLib.WebAdapter");
            return obj.GetClientVersion();
        }catch(ex){
            return "0.0.0";
        }
    },
    isClientSignedIn:function(){
        try{
            var obj = new ActiveXObject("PKToonLib.WebAdapter");
            return obj.IsClientSignedIn();
        }catch(ex){
            return false;
        }
    },
    genClientParamString:function(params, domainId, accountName){
        var client_version = PKUtil.getClientVersion();
        if (client_version == "0.0.0" && accountName != null) {
            return accountName;
        }else {
            var str = "";
            if (params != null) {
                params.each(function(pair){
                    str += pair.key + "=" + pair.value + ",";
                });
            }
            if (accountName != null) {
                str += "account_name=" + accountName + ",";
            }
            str = "client_version=" + client_version + ",domain_id=" + domainId + "," + str;
            return str;
        }
    },
    clientAct:function(action, reserved, domainId, params){
        try {
            var client_acting = PKToonWeb.Container.get("client_acting") ;
            if (client_acting != undefined && client_acting != null) {
                return;
            }
            if (!PKUtil.isClientInstalled()) {
                window.location.href="/help";
                return;
            }

            try {
                var obj = new ActiveXObject("PKToonLib.WebAdapter");
                if (obj.IsClientSignedIn()) {
                    var p = PKUtil.genClientParamString(params, domainId, null);
                    obj.ClientAct("", 0, 0, "", action, reserved, p);
                    return;
                }
            }catch(ex){}

            PKToonWeb.Container.set("client_acting", true);
            PKToonWeb.Container.set("client_act_action", action);
            PKToonWeb.Container.set("client_act_reserved", reserved);
            PKToonWeb.Container.set("client_act_params", params);
            PKToonWeb.Container.set("client_act_domain_id", domainId);

            var url = "/client/user/attach_session";
            new Ajax.Request(url,
            {
                method: "post",
                postBody: PKUtil.authenticityToken(),
                onSuccess: PKUtil.attachSessionResult,
                onFailure: PKUtil.attachSessionFailure
            }
            );
        }catch(ex){}
    },
    attachSessionResult:function(rsp){
        var result = rsp.responseText.evalJSON();

        var obj = new ActiveXObject("PKToonLib.WebAdapter");
        var p = PKUtil.genClientParamString(PKToonWeb.Container.get("client_act_params"), PKToonWeb.Container.get("client_act_domain_id"), result.account_name);
        obj.ClientAct(result.host, result.port, result.account_id, result.session_id, PKToonWeb.Container.get("client_act_action"), PKToonWeb.Container.get("client_act_reserved"), p);

        PKToonWeb.Container.unset("client_acting");
        PKToonWeb.Container.unset("client_act_action");
        PKToonWeb.Container.unset("client_act_reserved");
        PKToonWeb.Container.unset("client_act_params");
        PKToonWeb.Container.unset("client_act_domain_id");
    },
    attachSessionFailure:function(){
        PKToonWeb.Container.unset("client_acting");
        PKToonWeb.Container.unset("client_act_action");
        PKToonWeb.Container.unset("client_act_reserved");
        PKToonWeb.Container.unset("client_act_params");
        PKToonWeb.Container.unset("client_act_domain_id");
        window.location.href="/help";
    },
    copyToClip:function(text){
        PKUtil.copyLink(text);
        alert(NativeText.get("copied_to_clipboard"));
    },
    copyLink:function(link){
        if (window.clipboardData){
            window.clipboardData.setData("Text",link);
        }else{
            var flashcopier = 'flashcopier';
            if(!document.getElementById(flashcopier)){
                var divholder = document.createElement('div');
                divholder.id = flashcopier;
                document.body.appendChild(divholder);
            }
            document.getElementById(flashcopier).innerHTML = '';
            var divinfo = '<embed src="/medias/flash/flashcopier.swf" FlashVars="clipboard='+this.urlEncode(link)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
            document.getElementById(flashcopier).innerHTML = divinfo;
        }
    },
    addLog:function(action, relativeId, params){
        var url = "/action_log/add";
        var p = PKUtil.authenticityToken() + "&action_id=" + action + "&relative_id=" + relativeId + "&params=" + params;
        new Ajax.Request(url,
        {
            method: "post",
            postBody: p
        }
        );
    },
    addBannerClickingLog:function(pidId, position){
        PKUtil.addLog(16, pidId, position);
    },
    addWatchingMovieLog:function(mediaId){
        PKUtil.addLog(1, mediaId, null);
    },
    addSharingMovieLog:function(mediaId, method){
        PKUtil.addLog(2, mediaId, method);
    },
    addBrowsingTopicLog:function(topicId){
        PKUtil.addLog(3, topicId, null);
    },
    addBrowsingArticleLog:function(articleId){
        PKUtil.addLog(4, articleId, null);
    },
    addDownloadingClientLog:function(version){
        PKUtil.addLog(5, 0, version);
    },
    goToAction:function(mediaId){
        var autoClientTemplate = function(action, reserved, domainId, params){
            try {
                if (!PKUtil.isClientInstalled()) {
                    window.location.href="/help/download_guide";
                    $('forward_content').innerHTML = "";
                    $('forward_dialog').style.display    = 'none';
                    $('forward_bg').style.display        = 'none';
                    return;
                }

                try {
                    var obj = new ActiveXObject("PKToonLib.WebAdapter");
                    if (obj.IsClientSignedIn()) {
                        var p = PKUtil.genClientParamString(params, domainId, null);
                        obj.ClientAct("", 0, 0, "", action, reserved, p);
                        return;
                    }
                }catch(ex){}
                PKToonWeb.Container.set("client_acting", true);
                PKToonWeb.Container.set("client_act_action", action);
                PKToonWeb.Container.set("client_act_reserved", reserved);
                PKToonWeb.Container.set("client_act_params", params);
                PKToonWeb.Container.set("client_act_domain_id", domainId);

                var url = "/client/user/attach_session";
                new Ajax.Request(url,
                {
                    method: "post",
                    postBody: PKUtil.authenticityToken(),
                    onSuccess:function(rsp){
                        PKUtil.attachSessionResult(rsp);
                        location.href = '/my_pktoon' ;
                    },
                    onFailure: PKUtil.attachSessionFailure
                }
                );
            }catch(ex){}
        };
        var params = new Hash();
        params.set("MediaId",mediaId);
        PKUtil.addLog(14,mediaId,null);
        autoClientTemplate(1,0,1,params);
    }
};

PKUtil.Crypto = {
    // Place your application-specific JavaScript functions and classes here
    // This file is automatically included by javascript_include_tag :defaults

    // ===============================================================
    // = MD5 加密	                 								 =
    // ===============================================================

    hexcase : 0,  /* hex output format. 0 - lowercase; 1 - uppercase        */
    b64pad  : "", /* base-64 pad character. "=" for strict RFC compliance   */
    chrsz : 8,  /* bits per input character. 8 - ASCII; 16 - Unicode      */
  

    /*
   * These are the functions you'll usually want to call
   * They take string arguments and return either hex or base-64 encoded strings
   */
    hexMd5 : function (s){
        return PKUtil.Crypto.binl2hex(PKUtil.Crypto.coreMd5(PKUtil.Crypto.str2binl(s), s.length * PKUtil.Crypto.chrsz));
    },
  
    b64Md5 : function (s){
        return PKUtil.Crypto.binl2b64(PKUtil.Crypto.coreMd5(PKUtil.Crypto.str2binl(s), s.length * PKUtil.Crypto.chrsz));
    },
  
    hexHmacMd5 : function (key, data) {
        return PKUtil.Crypto.binl2hex(PKUtil.Crypto.coreHmacMd5(key, data));
    },
  
    b64HmacMd5 : function (key, data) {
        return PKUtil.Crypto.binl2b64(PKUtil.Crypto.coreHmacMd5(key, data));
    },
  
    /*
   * Convert a string to an array of little-endian words
   * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
   */
    str2binl : function (str)
    {
        var bin = Array();
        var mask = (1 << PKUtil.Crypto.chrsz) - 1;
        for(var i = 0; i < str.length * PKUtil.Crypto.chrsz; i += PKUtil.Crypto.chrsz)
            bin[i>>5] |= (str.charCodeAt(i / PKUtil.Crypto.chrsz) & mask) << (i%32);
        return bin;
    },

    /*
   * Convert an array of little-endian words to a hex string.
   */
    binl2hex : function (binarray)
    {
        var hex_tab = PKUtil.Crypto.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
        var str = "";
        for(var i = 0; i < binarray.length * 4; i++)
        {
            str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
            hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
        }
        return str;
    },

    /*
   * Convert an array of little-endian words to a base-64 string
   */
    binl2b64 : function (binarray)
    {
        var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var str = "";
        for(var i = 0; i < binarray.length * 4; i += 3)
        {
            var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
            | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
            |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
            for(var j = 0; j < 4; j++)
            {
                if(i * 8 + j * 6 > binarray.length * 32) str += PKUtil.Crypto.b64pad;
                else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
            }
        }
        return str;
    },

    /*
   * Calculate the MD5 of an array of little-endian words, and a bit length
   */
    coreMd5 : function (x, len)
    {

        /*
    * Add integers, wrapping at 2^32. This uses 16-bit operations internally
    * to work around bugs in some JS interpreters.
    */
        var safeAdd = function (x, y)
        {
            var lsw = (x & 0xFFFF) + (y & 0xFFFF);
            var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
            return (msw << 16) | (lsw & 0xFFFF);
        }
        /*
     * Bitwise rotate a 32-bit number to the left.
     */
        function bitRol(num, cnt)
        {
            return (num << cnt) | (num >>> (32 - cnt));
        }
        /*
     * These functions implement the four basic operations the algorithm uses.
     */
        var md5_cmn = function (q, a, b, x, s, t)
        {
            return safeAdd(bitRol(safeAdd(safeAdd(a, q), safeAdd(x, t)), s),b);
        };
        var md5_ff = function (a, b, c, d, x, s, t)
        {
            return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
        };
        var md5_gg = function (a, b, c, d, x, s, t)
        {
            return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
        };
        var md5_hh = function (a, b, c, d, x, s, t)
        {
            return md5_cmn(b ^ c ^ d, a, b, x, s, t);
        };
        var md5_ii = function (a, b, c, d, x, s, t)
        {
            return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
        };

        /* append padding */
        x[len >> 5] |= 0x80 << ((len) % 32);
        x[(((len + 64) >>> 9) << 4) + 14] = len;

        var a =  1732584193;
        var b = -271733879;
        var c = -1732584194;
        var d =  271733878;

        for(var i = 0; i < x.length; i += 16)
        {
            var olda = a;
            var oldb = b;
            var oldc = c;
            var oldd = d;

            a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
            d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
            c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
            b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
            a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
            d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
            c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
            b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
            a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
            d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
            c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
            b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
            a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
            d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
            c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
            b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

            a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
            d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
            c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
            b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
            a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
            d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
            c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
            b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
            a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
            d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
            c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
            b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
            a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
            d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
            c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
            b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

            a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
            d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
            c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
            b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
            a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
            d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
            c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
            b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
            a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
            d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
            c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
            b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
            a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
            d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
            c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
            b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

            a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
            d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
            c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
            b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
            a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
            d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
            c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
            b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
            a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
            d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
            c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
            b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
            a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
            d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
            c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
            b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

            a = safeAdd(a, olda);
            b = safeAdd(b, oldb);
            c = safeAdd(c, oldc);
            d = safeAdd(d, oldd);
        }
        return Array(a, b, c, d);
    },

    /*
   * Calculate the HMAC-MD5, of a key and some data
   */
    coreHmacMd5 : function (key, data)
    {
        var bkey = PKUtil.Crypto.str2binl(key);
        if(bkey.length > 16) bkey = PKUtil.Crypto.coreMd5(bkey, key.length * PKUtil.Crypto.chrsz);

        var ipad = Array(16), opad = Array(16);
        for(var i = 0; i < 16; i++)
        {
            ipad[i] = bkey[i] ^ 0x36363636;
            opad[i] = bkey[i] ^ 0x5C5C5C5C;
        }

        var hash = PKUtil.Crypto.coreMd5(ipad.concat(PKUtil.Crypto.str2binl(data)), 512 + data.length * PKUtil.Crypto.chrsz);
        return PKUtil.Crypto.coreMd5(opad.concat(hash), 512 + 128);
    },
  
    /*
   * Perform a simple self-test to see if the VM is working 
   */
    md5VmTest : function ()
    {
        return PKUtil.Crypto.hexMd5("abc") == "900150983cd24fb0d6963f7d28e17f72";
    },
  
    hmacMd5VmTest : function()
    {
        return PKUtil.Crypto.hexHmacMd5("abcdefg", "text") == "c01bf6076bc3cef91b790d1b0575dfad";
    }
};

//window.onerror = function(){return true;}
