var CONTEXTPATH = CONTEXTPATH || "";

function CharMode(iN) {
    if (iN >= 48 && iN <= 57) //数字
        return 1;
    if (iN >= 65 && iN <= 90) //大写
        return 2;
    if (iN >= 97 && iN <= 122) //小写
        return 4;
    else
        return 8;
}

//bitTotal函数
//计算密码模式
function bitTotal(num) {
    modes = 0;
    for (i = 0; i < 4; i++) {
        if (num & 1)
            modes++;
        num >>>= 1;
    }
    return modes;
}
//返回强度级别
function checkStrong(sPW) {
    if (sPW.length < 6)
        return 0; //密码太短
    Modes = 0;
    for (i = 0; i < sPW.length; i++) {
        //密码模式
        Modes |= CharMode(sPW.charCodeAt(i));
    }
    return bitTotal(Modes);
}

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

/**
 * 只能是字母
 * @return {TypeName}
 */
function onlyLetter(ch) {
    var filter = /^[A-Za-z0-9]+$/;
    return filter.test(ch);

}
/**
 * 只能是字母
 * @return {TypeName}
 */
function onlyLetter(ch) {
    var filter = /^[A-Za-z]+$/;
    return filter.test(ch);

}

var gM = gM || {
    debug: true,
    log: function () {
        /** CLEAN BEGIN **/
        gM.debug && window.console && window.console.log && window.console.log(arguments[0]);
        /** CLEAN END **/
    },
    imageError: function (target, type, size) {
        var $obj = $(target);
        if ($obj.data("errorImg") != null) {
            return;
        }
        $obj.data("errorImg", "XXXX");
        gM.log(type)

        if (type == "res_doc") {
            $obj.attr("src", CONTEXTPATH + "/images/uploading-word.png")
        } else if (type == 'res_video') {
            $obj.attr("src", CONTEXTPATH + "/images/uploading-video.png")
        } else if (type == 'head') {
            if (size == "30") {
                $obj.attr("src", CONTEXTPATH + "/images/avatar/default/30.png")
            } else if (size == "90") {
                $obj.attr("src", CONTEXTPATH + "/images/avatar/default/90.png")
            } else {
                $obj.attr("src", CONTEXTPATH + "/images/avatar/default/60.png")
            }

        } else {
            $obj.attr("src", CONTEXTPATH + "/images/uploading.png")
        }
    },
    imageErrorStudyIndex: function (target, type, size) {
        var $obj = $(target);
        if ($obj.data("errorImg") != null) {
            return;
        }
        $obj.data("errorImg", "XXXX");
        gM.log(type)
        if (size == "30") {
            $obj.attr("src", CONTEXTPATH + "/images/avatar/default/30.png")
        } else if (size == "90") {
            $obj.attr("src", CONTEXTPATH + "/images/avatar/default/90.png")
        } else {
            $obj.attr("src", CONTEXTPATH + "/images/user-01.png")
        }

    },
    getRID: function () {
        var arg = arguments[0] || "";
        var length = 0;
        while (length == 0) {
            var _id = Math.random();
            _id = (_id + "").substring(2, 10);

            if ($("#" + arg + _id).length == 0) {
                return arg + _id;
            }
        }
    },
    beginAjax: function () {
        gM.log("beginAjax")
    },
    endAjax: function () {
        gM.log("endAjax")
    },
    ajax: function (params) {
        gM.beginAjax();
        $.ajax({
            url: params['url'],
            data: params['data'] || {},
            type: params['type'] || "post",
            dataType: params['dataType'] || "json",
            beforeSend: function () {
                params.beforeSend && params.beforeSend();
            },
            complete: function () {
                gM.endAjax()
            },
            success: function (JsonData) {
                params.success && params.success(JsonData);
            },
            error: function () {
                params.error && params.error();
                gM.netError;
            }
        })
    },
    netError: function () {
        gM.log("错误");
    },
    downLoadNodes: function (nodeId) {
        window.open(CONTEXTPATH + "/download/nodes/" + nodeId + ".mooc")
    },
    viewNodes: function (nodeId,nodeName,itemId) {
    	if (typeof(itemId) == "undefined" || itemId == null){
    		itemId = 0;
    	}
        gM.ajax({
            url: CONTEXTPATH + "/view/nodes/" + nodeId+"/"+itemId + ".mooc",
            type: "get",
            dataType: "html",
            success: function (xhtml) {
                var $id = gM.getRID();
                $("#dialog_home").empty();
                var $div = $('<div id="' + $id + '"></div>');
                $div.css({"width": "800px", "height": "450px", "position": "relative"});
                $("#dialog_home").append($div);
                $div.html(xhtml);
                var tt = $.dialog({
                    title: typeof(nodeName)=="undefined"?'预览':'预览'+" : "+nodeName,
                    width: 800,
                    height: 450,
                    lock: true,
                    content: $div[0],
                    /**cancel: function () {
                        setTimeout(function () {
                            $("#" + $id).remove()
                        }, 500);
                    },**/
                    ok: false
                })
            }
        })
    },
    downLoadAttr: function (nodeId) {
        window.open(CONTEXTPATH + "/download/attr/" + nodeId + ".mooc")
    },
    viewAttr: function (nodeId) {
        gM.ajax({
            url: CONTEXTPATH + "/view/attr/" + nodeId + ".mooc",
            type: "get",
            dataType: "html",
            success: function (xhtml) {
                var $id = gM.getRID();
                var $div = $('<div id="' + $id + '"></div>');
                $div.css({"width": "800px", "height": "450px", "position": "relative"});
                $("#dialog_home").append($div);
                $div.html(xhtml);
                var tt = $.dialog({
                    title: '预览',
                    width: 800,
                    height: 450,
                    cancelValue: '关闭',
                    lock: true,
                    content: $div[0],
                    cancel: function () {
                        setTimeout(function () {
                            $("#" + $id).remove()
                        }, 500);
                    },
                    ok: false
                })
            }
        })
    },
    jsEnter: function (str) {
        var s = str.toLowerCase();
        if (s.indexOf("<table ") >= 0) {
            return str;
        }
        return str.replace(new RegExp("\n", 'g'), "<br>");
    },
    noData: function (noDataStr) {
        noDataStr = noDataStr || "暂无记录！";
        var _html = [];
        _html.push('<div class="view-empty">');
        _html.push('<div class="view-show">');
        _html.push('<i class="icon-e-point"></i>');
        _html.push('</div>');
        _html.push('<div class="view-intro">');
        _html.push(noDataStr);
        _html.push('</div>');
        _html.push('</div>');
        return _html.join("");
    }, getQuizTemplate: function (templateName) {
        return templateName;
//        return CONTEXTPATH + "/js/quiz-factory/template/" + templateName + ".jsp"
    },
    getUploadId: function (innerId) {
        /*html5uploader-upload_attr_node-file-0*/
        innerId = innerId || "";
        var uploadId = "";
        if (innerId.indexOf("-") == -1) {
            uploadId = innerId;
        } else {
            uploadId = innerId.substring(innerId.indexOf("-") + 1, innerId.length);
        }
        return "pro-" + uploadId;
    },
    reportType: function (t) {
        var p = {
            "10": "广告",
            "20": "标题党",
            "30": "不良言论",
            "40": "欺诈信息"
        }
        if (typeof p[String(t)] == "undefined") {
            return p['30'];
        }
        return p[String(t)];
    },
    showElement: function (e) {
        if ($(e).length > 0) {
            $(e).eq(0)[0].scrollIntoView(true);
        }
    },
    exportForum: function (actionUrl, option) {
        option = option || {};
        var form = document.createElement("form")
        form.action = actionUrl;
        form.method = "post";
        for (var i in option) {
            var input = document.createElement("input");
            input.name = i;
            input.value = option[i];
            form.appendChild(input);
        }
        document.body.appendChild(form);
        form.submit();
    },
    getString: function (obj) {
        var str = "";
        if (typeof obj != "undefined" && obj != null) {
            str += obj;
        }
        return str;
    }
}



function notEmpty() {
    var $target = arguments[0];
    if ($.trim($target.text()).length == 0 && $target.html().indexOf("mathquill-embedded-latex") < 0 && $target.html().indexOf("src") < 0) {
        return "<i class='icon-mark error-mark'></i>" + '帖子不能为空';
    }
    return;
}


if (!window.console) {
    window.console = {
        log: function (text) {
        },
        info: function (text) {
        }
    }
}

function Base64() {

    // private property
    var _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;
    }
}

function specialCharacters(str) {
    return /^[\w\u4e00-\u9fa5]+$/gi.test(str)
}

function checkSpecialCharacters(str) {
    var $target = arguments[0];
    gM.log($target.text())
    gM.log($target.html())
    if (specialCharacters($target.text() || $target.html() || $target.val())) {
        return
    }
    return "<i class='icon-mark error-mark'></i>" + "只能是数字、字母、汉字、\"_\"的组合";
}


//使用var myuuid=new UUID();

//On creation of a UUID object, set it's initial value
function UUID() {
    this.id = this.createUUID();
}


//When asked what this Object is, lie and return it's value
UUID.prototype.valueOf = function () {
    return this.id;
};
UUID.prototype.toString = function () {
    return this.id;
};


//
//INSTANCE SPECIFIC METHODS
//
UUID.prototype.createUUID = function () {
    //
    // Loose interpretation of the specification DCE 1.1: Remote Procedure Call
    // since JavaScript doesn't allow access to internal systems, the last 48 bits
    // of the node section is made up using a series of random numbers (6 octets long).
    //
    var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
    var dc = new Date();
    var t = dc.getTime() - dg.getTime();
    var tl = UUID.getIntegerBits(t, 0, 31);
    var tm = UUID.getIntegerBits(t, 32, 47);
    var thv = UUID.getIntegerBits(t, 48, 59) + '1'; // version 1, security version is 2
    var csar = UUID.getIntegerBits(UUID.rand(4095), 0, 7);
    var csl = UUID.getIntegerBits(UUID.rand(4095), 0, 7);

    // since detection of anything about the machine/browser is far to buggy,
    // include some more random numbers here
    // if NIC or an IP can be obtained reliably, that should be put in
    // here instead.
    var n = UUID.getIntegerBits(UUID.rand(8191), 0, 7) +
        UUID.getIntegerBits(UUID.rand(8191), 8, 15) +
        UUID.getIntegerBits(UUID.rand(8191), 0, 7) +
        UUID.getIntegerBits(UUID.rand(8191), 8, 15) +
        UUID.getIntegerBits(UUID.rand(8191), 0, 15); // this last number is two octets long
    return tl + tm + thv + csar + csl + n;
};


//Pull out only certain bits from a very large integer, used to get the time
//code information for the first part of a UUID. Will return zero's if there
//aren't enough bits to shift where it needs to.
UUID.getIntegerBits = function (val, start, end) {
    var base16 = UUID.returnBase(val, 16);
    var quadArray = new Array();
    var quadString = '';
    var i = 0;
    for (i = 0; i < base16.length; i++) {
        quadArray.push(base16.substring(i, i + 1));
    }
    for (i = Math.floor(start / 4); i <= Math.floor(end / 4); i++) {
        if (!quadArray[i] || quadArray[i] == '') quadString += '0';
        else quadString += quadArray[i];
    }
    return quadString;
};


//Replaced from the original function to leverage the built in methods in
//JavaScript. Thanks to Robert Kieffer for pointing this one out
UUID.returnBase = function (number, base) {
    return (number).toString(base).toUpperCase();
};


//pick a random number within a range of numbers
//int b rand(int a); where 0 <= b <= a
UUID.rand = function (max) {
    return Math.floor(Math.random() * (max + 1));
};

(function ($) {
    if (typeof window.JSON == "undefined") {
        return;
    }
    gM.parseJSON = window.JSON.parse;
    window.JSON.parse = function (data) {
        var _r = {}
        try {
            _r = gM.parseJSON(data)
            return _r;
        } catch (e) {
            gM.log("JSON.parse error " + data);
        }
        var rvalidchars = /^[\],:{}\s]*$/,
            rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
            rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
            rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g;
        if
            (data === null) {
            return data;
        }

        if (typeof data === "string") {

            // Make sure leading/trailing whitespace is removed (IE can't handle it)
            data = jQuery.trim(data);

            if (data) {
                // Make sure the incoming data is actual JSON
                // Logic borrowed from http://json.org/json2.js
                if (rvalidchars.test(data.replace(rvalidescape, "@")
                    .replace(rvalidtokens, "]")
                    .replace(rvalidbraces, ""))) {

                    return ( new Function("return " + data) )();
                }
            }
        }
    }
})($ || jQuery);

