﻿var loadingImg1 = "<span class=\"loading1\"></span>"; //<img src=\"/Images/v2/loading1.gif\" alt=\"loading\" />";
var loadingImg2 = "<span class=\"loading2\"></span>"; //"<img src=\"/Images/v2/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");
    });
});

var pageX = 0;
var pageY = 0;

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");
        });
//    var menuParentOffset = menu.parent().offset();
//    var menuOffset = $("#topmenu").offset();//get menu's offset , but IE8/FF/Chrome couldn't read the right offset by "menu", so using 'div#topmenu' here.
//    var menuWidth = parseInt(menu.width());
//    menu.children("li").hover(function () {
//        var thisLI = $(this);
//        thisLI.addClass("current_temp");
//        if (thisLI.children("ul").size() == 0) {
//            return;
//        }

//        var subMenu = thisLI.children("ul").eq(0);
//        var topmenuLiOffset = thisLI.children("a.topmenu").eq(0).offset(); //get current LI(a.topmenu)'s offset
//        //alert("topmenuLiOffset.top:" + topmenuLiOffset.top + " , topmenuLiOffset.left:" + topmenuLiOffset.left + " , #topmenu Left:" + menuOffset.left);
//        //var position = subMenu.position();
//        menu.animate({ "margin-top": "1px" }, 100);
//        //alert("topmenuLiOffset.left:" + topmenuLiOffset.left + " , subMenu.width():" + subMenu.width() + " ,thisLI.width():" + thisLI.width());
//        var subMenuLeft = topmenuLiOffset.left - ((parseInt(subMenu.width()) - parseInt(thisLI.width())) / 2);
//        //alert("subMenuLeft:"+subMenuLeft+",subMenuWidth:" +subMenu.width()+ "|"+(subMenuLeft + subMenu.width()) + "," + (parseInt(menuOffset.left) + menuWidth));
//        if (subMenuLeft + subMenu.width() >= menuOffset.left + menuWidth - 20) {
//            //            alert((subMenuLeft + subMenu.width()) + "," + (parseInt(menuOffset.left) + menuWidth));
//            subMenuLeft = menu.offset().left + menuWidth - subMenu.width() - 20;
//        }
//        else if (subMenuLeft <= menuOffset.left + 20) {
//            subMenuLeft = menuOffset.left + 20;
//        }

//        subMenu.css({ top: (menuParentOffset.top + 18), left: subMenuLeft })
//              .slideDown(50, 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 () {
//        var $this = $(this);
//        $this.removeClass("current_temp");
//        $this.children("ul").hide(); //fadeOut();
//        pageX = 0;
//        pageY = 0;

//        setTimeout(function () {
//            var current_temp = $this.siblings("li.current_temp");
//            if (current_temp.size() == 0 || (current_temp.find("ul").size() > 0 && current_temp.find("ul:visible").size() == 0)) {
//                menu.find("li ul").hide(); //ensure all the submenu hided.
//                menu.find("li.current_temp").removeClass("current_temp");
//                menu.animate({ "margin-top": "18px" }, 100);
//            }
//        }, 110);
//    });



//    menu.find("li ul").mousemove(function (e) {
//        if (menu.css("margin-top") != "1px" || menu.css("margin-top") != "1") {
//            menu.css({ "margin-top": "1px" });
//        }
//    });

    //    menu.children("li").children("ul").mousemove(function (e) {
    //        if (pageX > 0) {
    //            var diff = (parseInt(e.pageX) - parseInt(pageX));
    //            //if (Math.abs(diff) > 0) {
    //                var position = $(this).position();
    //                $(this).animate({ left: (position.left - diff) }, 100);
    //                pageX = parseInt(e.pageX);
    //                pageY = parseInt(e.pageY);
    //            //}
    //        }
    //        else {
    //            pageX = parseInt(e.pageX);
    //            pageY = parseInt(e.pageY);
    //        }
    //    }).mouseout(function () {
    //        pageX = 0;
    //        pageY = 0;
    //    });

    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, pagerStyle) {
    var currentPageIndex = pageIndex;
    var pagerId = contentId + "_jPagerBar";
    var loadingId = contentId + "_loading";
    var pagerStyle = pagerStyle==null?"quotes":pagerStyle;
    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 + ",'" + pagerStyle + "');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>");
}
