﻿/***
 * -CLASS-
 * @name CuiCore
 * @package cui.core
 * @description 核心类库
 * @pageTag
 * @example
 * @author ypu
 * @version 2011-08-03
 * @since 0.1
 */
var CuiCfg = {};
CuiCfg.ajaxTip = true;
CuiCfg.debug = false;
String.prototype.replaceAll = function(s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}
;
(function($) {
    $.extend({
        /**
         * -METHOD-
         * @summary ajax提交
         * @description  ajax提交（非form），自动处理返回格式为{status:,msg:}的内容（status为200，操作成功）.返回提示msg的信息，同时也处理网络出错提示。
         * @method cuiAjax
         * @param form string/json <提交的url或者form的json对象>
         * @param url string <form提交的url> form
         * @param dataType string <form提交的数据类型，可选，默认json> form
         * @param type string <form提交的类型，可选，默认post> form
         * @param params json <from提交附带的参数，可选>
         * @param func function <from提交出错或成功的回调函数，可选，返回参数为Object，boolean（操作是否成功）>
         * @return none
         * @since 0.1
         */
        cuiAjax:function(url, params, func) {
            var form;
            if (typeof url == 'string') {
                form = {};
                form.url = url;
            } else {
                form = url;
            }

            if (params)form.data = params;
            if (!form.dataType)form.dataType = 'json';
            if (!form.type)form.type = 'post';
            if (!form.contentType)form.contentType = 'application/x-www-form-urlencoded;charset=UTF-8';

            form.error = function(jq, text, error) {
                if(CuiCfg["debug"]){
                    $.cuiLog('cuiAjax',text);
                }
                if (CuiCfg["ajaxTip"]) {
                    if (text == 'timeout') {
                        CuiOverWarn(CuiRes.TIME_OUT);
                    } else {
                        CuiOverWarn(CuiRes.NET_ERROR);
                    }
                }
                if (func)func(jq.responseText, false);
            }
            form.success = function(o) {
                try {
                    if (typeof o == 'string')o = eval('(' + o + ')');
                } catch(e) {

                }
                if (CuiCfg["debug"]) {
                    $.cuiLog('cuiAjax', o);
                }
                if (CuiCfg["ajaxTip"] && o && o.status) {
                    if (o.status == 200) {
                        if (CuiCfg["ajaxTip"] && o.msg)CuiOverAlert(o.msg);
                        if (func)func(o, true);
                    } else {
                        if (CuiCfg["ajaxTip"] && o.msg)CuiOverWarn(o.msg);
                        if (func)func(o, false);
                    }
                } else {
                    if (func)func(o, true);
                }
            }
            $.ajax(form);
        },
        /**
         * -METHOD-
         * @summary ajax提交form
         * @description  ajax提交form，自动处理返回格式为{status:,msg:}的内容（status为200，操作成功）。返回提示msg的信息，同时也处理网络出错提示。
         * @method cuiAjaxForm
         * @param id string/object <提交form的id、class，或者form的jquery对象>
         * @param form string/json <提交的url或者form的json对象>
         * @param url string <form提交的url> form
         * @param dataType string <form提交的数据类型，可选，默认json> form
         * @param type string <form提交的类型，可选，默认post> form
         * @param func function <from提交出错或成功的回调函数，可选，返回参数为Object，boolean（操作是否成功）>
         * @param params json <from提交附带的参数，可选>
         * @return none
         * @since 0.1
         */
        cuiAjaxForm:function(id, url, func, params) {
            var form;
            var setting;
            if (typeof id == 'string') {
                form = $('#' + id);
                if (form.length == 0)form = $('.' + id);
                if (form.length == 0)return null;
            } else {
                form = id;
            }
            try {
                if (form.length != 1 || !form.is('form')) {
                    return null;
                }
            } catch(e) {
                return null;
            }
            if (typeof url == 'string') {
                setting = {};
                setting.url = url;
            } else {
                setting = url;
            }

            if (params)setting.data = params;
//            if (!setting.dataType)setting.dataType = 'json';
            if (!setting.type)setting.type = 'post';
            if (!setting.contentType)setting.contentType = 'application/x-www-form-urlencoded;charset=UTF-8';

            setting.error = function(jq, text, error) {
                if (CuiCfg["debug"]) {
                    $.cuiLog('cuiAjax', text);
                }
                if (text == 'timeout') {
                    CuiOverWarn(CuiRes.TIME_OUT);
                } else {
                    CuiOverWarn(CuiRes.NET_ERROR);
                }
                if (func)func(jq.responseText, false);
            }
            setting.success = function(o) {
                if (CuiCfg["debug"]) {
                    $.cuiLog('cuiAjax', o);
                }
                try {
                    if (typeof o == 'string')o = eval('(' + o + ')');
                } catch(e) {

                }
                if (o && o.status) {
                    if (o.status == 200) {
                        if (o.msg)CuiOverAlert(o.msg);
                        if (func)func(o, true);
                    } else {
                        if (o.msg)CuiOverWarn(o.msg);
                        if (func)func(o, false);
                    }
                } else {
                    if (func)func(o, true);
                }
            }
            form.ajaxSubmit(setting);
        },
        cuiHighLight:function(o,key,style){
            if(typeof key =='undefined')return o;

            if(typeof o =="object"){
                for(var i in o){
                    o[i] = this.cuiHighLight(o[i],key,style);
                }
                return o;
            }else if(typeof o == "string"){
                o = o.replaceAll(key, '<span class="'+(typeof style == "string"?style:'cui_highLight')+'">' + key + '</span>');
                return o;
            }else{
                return o;
            }
        },
        cuiLoadJS:function(url, callback, charset) {
            var script = document.createElement('script');
            script.onload = script.onreadystatechange = function () {
                if (script && script.readyState && /^(?!(?:loaded|complete)$)/.test(script.readyState)) return;
                script.onload = script.onreadystatechange = null;
                script.src = '';
                script.parentNode.removeChild(script);
                script = null;
                if (callback)callback();
            };
            script.charset = charset || document.charset || document.characterSet;
            script.src = url;
            try {
                document.getElementsByTagName("head")[0].appendChild(script);
            } catch (e) {
            }
        },
        cuiShortStr:function(str,length,brief){
            if(str.length <= length)return str;
            str = str.substr(0,length);
            if(brief){
                return str+brief;
            }else{
                return str+"......";
            }
        },
        cuiLog:function(key,str){
            var msg = '['+key+'] ' + str;
            if (window.console && window.console.log) {
                window.console.log(msg);
            }
            else if (window.opera && window.opera.postError) {
                window.opera.postError(msg);
            }
        },
        cuiNumber2Size:function(num, pos) {
            if(typeof pos == 'undefined')pos = 2;
            var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
            var e = Math.floor(Math.log(num) / Math.log(1024));
            return (num / Math.pow(1024, Math.floor(e))).toFixed(pos) + s[e];
        },
        cuiRandom:function(num){
            var today = new Date();
            var seed = today.getTime();
            seed = (seed * 9301 + 49297) % 233280;
            return Math.ceil(seed / (233280.0) * num);
        },
        cuiCheckFileExt:function(filename, limitExt) {
            if (limitExt === '*' || filename.match(new RegExp('\.(' + limitExt.replace(/,/g, '|') + ')$', 'i')))return true;
            else {
                return false;
            }
        }

    });
})(jQuery);
///EndClassubmit(setting);(setting);ssubmit(setting);(setting);
