﻿$.extend({
    includePath: '',
    include: function(file) {
        var files = typeof file == "string" ? [file] : file;
        for (var i = 0; i < files.length; i++) {
            var name = files[i].replace(/^\s|\s$/g, "");
            var att = name.split('.');
            var ext = att[att.length - 1].toLowerCase();
            var isCSS = ext == "css";
            var tag = isCSS ? "link" : "script";
            var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
            var link = (isCSS ? "href" : "src") + "='" + $.includePath + name + "'";
            if ($(tag + "[" + link + "]").length == 0) document.write("<" + tag + attr + link + "></" + tag + ">");
        }
    }
});

$.fn.extend({
    onlypressnum: function() {
        return $(this).each(function() {
            $(this).css({ imeMode: "disabled", '-moz-user-select': "none" });
            $(this).bind("keypress", function(e) {
                if (e.ctrlKey == true || e.shiftKey == true) return false;
                if ((e.which >= 48 && e.which <= 57 && e.ctrlKey == false && e.shiftKey == false) || e.which == 0 || e.which == 8) return true;
                else if (e.ctrlKey == true && (e.which == 99 || e.which == 118)) return false;
                else return false;
            }).bind("contextmenu", function() { return false; })
             .bind("selectstart", function() { return false; })
             .bind("drop", function() { return false; })
             .bind("paste", function() { return false; });
        });
    },
    hoverClass: function(c) {
        return this.each(function() {
            $(this).hover(function() { $(this).addClass(c); },function() { $(this).removeClass(c); });
        });
    },
    check: function() {
        var r = true;
        $(this).find("input.require,select.require,textarea.require").each(function() {
            var $this = $(this);
            if ($this.val().length <= 0) {
                $this.focus();
                showMessage("info", "系统提示：输入不完整");
                r = false;
                return false;
            }
        });
        return r;
    },
    // json data to bind form input.
    bindField: function(data) {
        var $this = $(this);
        $.each(data, function(i) {
            var val = data[i];
            if (val == null) val = '';
            else if (typeof val == "object") return true;
            var $obj = $('#' + i);
            if ($obj.length == 0) {
                $obj = $("input[name='" + i + "']");
                if ($obj.length == 0) {
                    $obj = $("<input type='hidden' id='" + i + "' name='" + i + "'/>").appendTo($this);
                }
            }
            switch ($obj.attr("type")) {
                case "checkbox": case "radio":
                    $obj.attr("checked", false).filter("[value='" + val + "']").attr("checked", true);
                    break;
                case "text": case "hidden": case "button": case "password":
                    $obj.val(val);
                    break;
                default:
                    $obj.text(val);
                    break;
            }
        });
    }
})

$.extend({
    Log: function(opts) {
        var $obj = $(document.activeElement);
        var title = document.title;
        var now = new Date();
        var data = { URL: opts.url, TYPE: opts.type, DATA: opts.data, TITLE: title, MESSAGE:opts.message, DATE: formatDate(now), TIME: formatTime(now), OPERATOR: user.USER_CODE };
        $.ajax({ global: false, type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", url: "../../service/LIBRARY.svc/LOG", data: JSON.stringify(data) });
    },
    Filter: function(opts) {
        if (!opts.url && opts.data && opts.data.__metadata) opts.url = opts.data.__metadata.uri;
        if (opts.url.indexOf("LIBRARY.svc") == -1) opts.url = "../../service/LIBRARY.svc/" + opts.url
        if (typeof opts.data == "object") opts.data = JSON.stringify(opts.data);
    },
    Insert: function(opts) {
        $.Filter(opts);
        $.extend(opts, { type: "POST", dataType: "json", contentType: "application/json; charset=utf-8" });
        $.ajax(opts);
        $.Log(opts);
    },

    Update: function(opts) {
        $.Filter(opts);
        $.extend(opts, { type: "PUT", contentType: "application/json; charset=utf-8" });
        $.ajax(opts);
        $.Log(opts);
    },

    Delete: function(opts) {
        $.Filter(opts);
        $.extend(opts, { type: "DELETE" });
        $.ajax(opts);
        $.Log(opts);
    }
});


function ajaxLoader() {
    var loader = $("<img id='loading' src='../../images/loading.gif'>").appendTo(document.body).ajaxStart(function() {
        $(this).show();
    }).ajaxStop(function() {
        $(this).hide();
    }).ajaxError(function(a, b, e) {
        $(this).hide();
        //var message = $("message", b.responseXML).text().replace(/\\u/g, "%u");
        var message = b.responseText.replace(/\\u/g, "%u");
        $.Log({ url: e.url, type: e.type, data: e.data, message: message });
        if (message && message != "") alert("系统异常信息提示：\n" + message);
    });
}

function showMessage(msgType, text, sec) {
    if (!msgType) msgType = "info";
    if (!text) text = "保存操作成功.";
    var html = "<div class='msgbox' style='background-image:url(../../images/icon/" + msgType + ".gif)'>" + text + "</div>";
    var msgbox = $(html).appendTo(document.body).animate({ top: -2 });
    if(msgType=="info"){
        msgbox.animate({ top: -2 }, sec || 2000).slideUp("slow", function() { $(this).remove() });
    }
    else{
        $("<img style='position:absolute;top:3px;right:3px' src='../../images/icon/close.gif'>").appendTo(msgbox).click(function(){msgbox.remove()});
    }
}

function addDays(theDate, amount) { return new Date(theDate.getTime() + amount * 86400000); }
function parseDate(theDate) { theDate += ""; return new Date(theDate.substring(0, 4), parseInt(theDate.substring(4, 6), 10) - 1, theDate.substring(6, 8)) }
function formatDate(theDate) { return theDate.getFullYear() * 10000 + (theDate.getMonth() + 1) * 100 + theDate.getDate() + "" }
function formatTime(theDate) {
    var h = "0" + theDate.getHours();
    var m = "0" + theDate.getMinutes() + "";
    var s = "0" + theDate.getSeconds() + "";
    return h.substring(h.length - 2, h.length) + ":" + m.substring(m.length - 2, m.length) + ":" + s.substring(s.length - 2, s.length);
}

function flash(file,w,h) {
    document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="'+w+'" height="'+h+'"> ');
    document.write('<param name="movie" value="' + file + '">');
    document.write('<param name="quality" value="high"> ');
    document.write('<param name="wmode" value="transparent"> ');
    document.write('<param name="menu" value="false"> ');
    document.write('<embed src="' + file + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="'+w+'" height="'+h+'" wmode="transparent"></embed> ');
    document.write('</object> ');
}