﻿var loadingImg1 = "<span class=\"loading1\"></span>"; //<img src=\"/Images/loading1.gif\" alt=\"loading\" />";
var loadingImg2 = "<span class=\"loading2\"></span>"; //"<img src=\"/Images/loading2.gif\" alt=\"loading\" />";
var faqItemUrlFormat = "/FAQ-{id}.xhtml";

$(document).ready(function () {
    $("#footermenu li:first").css("background", "");
    $("table.datatable tr").hover(function () {
        $(this).addClass("hover");
    }, function () {
        $(this).removeClass("hover");
    });
});

function openSubMenu(menuId) {
    var menu = $("#" + menuId);
    menu.children("li").hover(function () {
        var thisLI = $(this);
        var offset = thisLI.children("a").eq(0).offset();
        thisLI.addClass("current_temp");
        thisLI.children("ul").eq(0).css({ top: offset.top, left: offset.left })
              .slideDown("fast", function () {
                  thisLI.addClass("current_temp"); //ensure the  current item has the current-class
                  //hide other menus in display
                  var visibleUL = thisLI.siblings().children("ul:visible");
                  visibleUL.hide().closest("li").removeClass("current_temp");
              });
    }, function () {
        $(this).children("ul").hide(); //fadeOut();
        $(this).removeClass("current_temp");
    });

    menu.find("li ul").find("li:last a").css({ "border-bottom": "" });
}


function setHomePage(obj) {
    var aUrls = document.URL.split("/");
    var vDomainName = "http://" + aUrls[2] + "/";
    try {//IE 
        obj.style.behavior = "url(#default#homepage)";
        obj.setHomePage(vDomainName);
    } catch (e) {//other 
        if (window.netscape) {//ff 
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (e) {
                alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将[signed.applets.codebase_principal_support]设置为'true'");
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage', vDomainName);
        }
    }
    //if (window.netscape) alert("ff");
}

function addFavorite() {
    var aUrls = document.URL.split("/");
    var vDomainName = "http://" + aUrls[2] + "/";
    var description = document.title;
    try {//IE 
        window.external.AddFavorite(vDomainName, description);
    } catch (e) {//FF 
        window.sidebar.addPanel(description, vDomainName, "");
    }
}

/**  HTMLEncode & HTMLDecode **/
function HTMLEncode(html) {
    var temp = document.createElement("div");
    (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
    var output = temp.innerHTML;
    temp = null;
    return output;
}

function HTMLDecode(text) {
    var temp = document.createElement("div");
    temp.innerHTML = text;
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
}

function TextAreaHtmlDecode(textarea) {
    try {
        if (textarea.innerHTML) {
            textarea.innerHTML = HTMLDecode(textarea.innerHTML);
        }
    }
    catch (e) {
    }
}

function SetFCKEditor(fckName, html) {
    if (typeof (FCKeditorAPI) == 'undefined') {
        return false;
    }
    var oEditor = FCKeditorAPI.GetInstance(fckName);
    if (oEditor.EditorDocument != null) {
        oEditor.EditorDocument.body.innerHTML = html;
    }
    else if (typeof (oEditor.EditingArea) != 'undefined'
                && typeof (oEditor.EditingArea.Textarea) != 'undefined') {
        //textStr is more suitable compared with htmlStr
        oEditor.EditingArea.Textarea.innerText = html;
    }
}

/**  UrlEncode & UrlDecode **/
function UrlEncode(str) {
    var ret = "";
    var strSpecial = "!\"#$%&'()*+,/:;<=>?[]^`{|}~%";
    for (var i = 0; i < str.length; i++) {
        var chr = str.charAt(i);
        var c = str2asc(chr);
        tt += chr + ":" + c + "n";
        if (parseInt("0x" + c) > 0x7f) {
            ret += "%" + c.slice(0, 2) + "%" + c.slice(-2);
        } else {
            if (chr == " ")
                ret += "+";
            else if (strSpecial.indexOf(chr) != -1)
                ret += "%" + c.toString(16);
            else
                ret += chr;
        }
    }
    return ret;
}
function UrlDecode(str) {
    var ret = "";
    for (var i = 0; i < str.length; i++) {
        var chr = str.charAt(i);
        if (chr == "+") {
            ret += " ";
        } else if (chr == "%") {
            var asc = str.substring(i + 1, i + 3);
            if (parseInt("0x" + asc) > 0x7f) {
                ret += asc2str(parseInt("0x" + asc + str.substring(i + 4, i + 6)));
                i += 5;
            } else {
                ret += asc2str(parseInt("0x" + asc));
                i += 2;
            }
        } else {
            ret += chr;
        }
    }
    return ret;
}

//载入随鼠标移动的Tip
function loadTip(position) {
    $("[myTip]").hover(function () {
        $('<div id="Tip"><div class="triangle' + position + '" /></div>')
        .insertAfter(this)
        .prepend($(this).attr("myTip"));
        $(this).mousemove(function (e) {
            e = e || window.event;
            var x = e.pageX - 36;
            var y = e.pageY + 18;
            switch (position) {
                case "r":
                    y = e.pageY - 24;
                    x = e.pageX + 22;
                    break;
                case "b":
                    break;
                default:
                    break;
            }

            if (x - 2 < 0)
                x = 2;
            if (x + 152 > document.body.clientWidth)
                x = document.body.clientWidth - 152;
            $("#Tip").css({ "left": x, "top": y, "display": "block" });
        });
    }, function () {
        $("#Tip").remove();
    })
}


/**  复选框列表  **/

//验证是否有选中项
function CheckChecked(containerId) {
    if ($("#" + containerId).find("input:checkbox:checked").size() > 0) {
        return true;
    }
    else {
        alert("请选择至少一项！");
        return false;
    }
}

//获取被选中的值，用","分隔
function GetCheckedValues(containerId) {
    var ids = "";
    $("#" + containerId).find("input:checkbox:checked").each(function () {
        ids += $(this).val() + ",";
    });
    return ids;
}


//反选
function InvertCheckAll(containerId, checkBoxName) {
    if (containerId != null && containerId != "") {
        $("#" + containerId).find("input:checkbox").each(function () {
            $(this).attr("checked", !$(this).attr("checked"));
        });
    }
    else {
        $("input:checkbox[name='" + checkBoxName + "']").each(function () {
            $(this).attr("checked", !$(this).attr("checked"));
        });
    }
}

//全选
function CheckAll(containerId, checked) {
    $("#" + containerId).find("input:checkbox").each(function () {
        $(this).attr("checked", checked);
    });
}


/* 获得绝对位置坐标 */
function CPos(x, y) {
    this.x = x;
    this.y = y;
}

function GetObjPos(ATarget) {
    var target = ATarget;
    var pos = new CPos(target.offsetLeft, target.offsetTop);

    var target = target.offsetParent;
    while (target) {
        pos.x += target.offsetLeft;
        pos.y += target.offsetTop;

        target = target.offsetParent
    }

    return pos;
}
/* 获得绝对位置坐标 */


/* 图片锁定宽、高比 */
function Resizeimage(objImage, maxWidth, maxHeight) {
    //TODO:没有图片时候显示“没有图片”
    var sourceImg = $(objImage);
    var outputWidth = 0, outputHeight = 0;
    if (sourceImg.width() > sourceImg.height()) {
        if (sourceImg.width() > maxWidth) {
            outputWidth = maxWidth;
            outputHeight = (sourceImg.height() * maxWidth) / sourceImg.width();
        }
        else {
            outputWidth = sourceImg.width();
            outputHeight = sourceImg.height();
        }
    }
    else {
        if (sourceImg.height() > maxHeight) {
            var rate = (maxHeight / sourceImg.height());
            outputWidth = sourceImg.width() * rate;
            outputHeight = maxHeight;
        }
        else {
            outputWidth = sourceImg.width();
            outputHeight = sourceImg.height();
        }
    }

    sourceImg.width(outputWidth).height(outputHeight);
}

/* JSON <==> String */
function jsonToString(obj) {
    var THIS = this;
    switch (typeof (obj)) {
        case 'string':
            return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
        case 'array':
            return '[' + obj.map(THIS.jsonToString).join(',') + ']';
        case 'object':
            if (obj instanceof Array) {
                var strArr = [];
                var len = obj.length;
                for (var i = 0; i < len; i++) {
                    strArr.push(THIS.jsonToString(obj[i]));
                }
                return '[' + strArr.join(',') + ']';
            } else if (obj == null) {
                return 'null';

            } else {
                var string = [];
                for (var property in obj) string.push(THIS.jsonToString(property) + ':' + THIS.jsonToString(obj[property]));
                return '{' + string.join(',') + '}';
            }
        case 'number':
            return obj;
        case false:
            return obj;
    }
}

function stringToJSON(obj) {
    return eval('(' + obj + ')');
}


//赋值
function copy(value) {
    window.clipboardData.setData('text', value);
}


//jpagerbar
function TurnToPage(pageIndex, contentId, pageCount, requestUrl, itemUrlFormat,showPageNumber) {
    var currentPageIndex = pageIndex;
    var pagerId = contentId + "_jPagerBar";
    var loadingId = contentId + "_loading";
    var pagerStyle = "quotes";
    var pagerBarContainer = $("#" + pagerId);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: requestUrl,
        data: {"pageIndex":pageIndex,"showPageNumber":showPageNumber},  //+ "&pageCount=" + pageCount + "&action=" + action + "&orderby=" + orderBy + "", //数据
        beforeSend: function () { $("#" + loadingId).show(); /*pagerBarContainer.hide();*/ }, //发送数据之前
        complete: function () { $("#" + loadingId).hide(); /*pagerBarContainer.show();*/ }, //接收数据完毕
        success: function (json) {
            //数据获取完毕，填充页面据显示
            //数据列表
            var content = $("#" + contentId);
            var html = "<ul>";
            $.each(json.data, function (i, item) {
                html += "<li><a href=\"" + itemUrlFormat.replace("{id}", item.Id) + "\">" + item.Title + "</a></li>";
            });
            html += "</ul>";
            content.html(html);

            //页码
            pagerBarContainer.showPageBar(
                    "", //[url]
                    {style: pagerStyle, mark: contentId + "_pageDataList1Mark",
                    totalCount: json.totalCount, showPageNumber: showPageNumber, pageCount: pageCount, currentPageIndex: pageIndex, noRecordTip: "没有记录", preWord: "<", nextWord: ">",
                    onclick: "TurnToPage({pageindex},'" + contentId + "','" + pageCount + "','" + requestUrl + "','" + itemUrlFormat + "',"+showPageNumber+");return false;"
                } //[attr]
                    );
        }
    });
}

//帮助信息
function faqhelp(id, faqId) {
    $("#" + id).html("[<a href=\"" + faqItemUrlFormat.replace("{id}", faqId) + "\">?</a>]");
}

//载入验证码
function loadCheckCode(containerId, id) {
    $("#" + containerId).html(
    "<img alt='验证码，不区分大小写' src='/Home.xhtml/Checkcode/" + id.toString() + "?t=" + Math.random() + "' class=\"checkcode\" />" +
    " 不区分大小写，<a href=\"javascript:void(0);\" onclick=\"loadCheckCode('" + containerId + "','" + id + "');\">看不清点击这里</a>");
}