﻿// common.js 系统公共js
// 版本 1.0.0
// 组件： autoComplete
/*
常量
*/



/*
* AutoComplete
*/
function AutoCompletehide(Id) {
    $("#" + Id).css("visibility", "hidden");
    var ie6 = $.browser.msie && ($.browser.version == "6.0");
    if (ie6) $("#ie6_iframe").css("height", "0");
}

function AutoComplete(ctrlId, uri, fn) {
    //css
  var autoCompleteCss = '<style id="mycss" type="text/css"> .actable{ background-color:#fff; font-size:12px; } .actable td{ line-height:17px;cursor:default; white-space:nowrap; } ';
  autoCompleteCss += '.dic{padding: 0 0 0 3px; width:250px; text-align: left; overflow:hidden; }';
  autoCompleteCss += '.did, .die{padding: 0 3px 0 0;text-align: right;color: Green;}';
  autoCompleteCss += '.dib td{ background: #3366CC none repeat scroll 0 0; color: #fff; white-space: nowrap; }</style>';
var timer=undefined;
var isClose = false;
var iskeydown = -1;
    var isSelecting = true;
    var obj = $("#" + ctrlId); //获取需要添加autocomplete对象控件
    var retData = "";
    var divId = ctrlId + "_acc"; //弹出列表框架ID
    //定义是否IE6
    var ie6 = $.browser.msie && ($.browser.version == "6.0");
    var divIdObj = $("#" + divId);
    
    var tablehtml = '<table id=' + divId + ' name=' + divId + ' class="actable"   cellpadding="0" cellspacing="0" style="border:#333 1px solid ;z-index:10; visibility: hidden;position:absolute "><tbody></tbody></table>';
    var modifiedwidth = function() {//修正弹出ID的位置
        if ($.browser.msie) return 6;
        if ($.browser.mozilla) return 5;
        if ($.browser.safari) return 4;
        if ($.browser.opera) return 6;
      };
    
    var relativeLeft = function() {//修正弹出ID的相对Left的位置
      if ($.browser.msie) return 0;
      if ($.browser.mozilla) return 1;
      if ($.browser.safari) return 0;
      if ($.browser.opera) return 0;
    };
    
    obj.parent().append(tablehtml);
    //$("#" + divId).css({ 'width': obj.width() + modifiedwidth() + 'px', 'top': obj.height() + obj.offset().top + 4 + 'px', 'left': obj.offset().left + 'px' });
    $("#" + divId).css({ 'width': obj.width() + modifiedwidth() + 'px', 'top': obj.height() + 10 + 'px', 'left': relativeLeft() + 'px' });
   // alert($("#" + divId).css('width'));
    if ($("#mycss").length == 0) $('head').prepend(autoCompleteCss);
    obj.blur(function() { if (!isSelecting) AutoCompletehide(divId); iskeydown = -1; });
    $("#" + divId).mouseover(function() { isSelecting = true; });
    $("#" + divId).mouseout(function() { isSelecting = false; });
    
    //** $(window).unbind().resize(function() { $("#" + divId).css({ 'width': obj.width() + 3, 'top': obj.height() + obj.offset().top + 4, 'left': obj.offset().left }); });
    $("#" + divId).css({ 'width': obj.width() + modifiedwidth() + 'px', 'top': obj.height() + 10 + 'px', 'left': relativeLeft() + 'px' });
    
    $("#" + divId + " tr ").live("mouseover", function() { $("#" + divId + " tr ").attr("class", ''); $(this).attr("class", "dib"); });
    $("#" + divId + " tr").live("click", function() { if ($(this).find('.die').length > 0) return; obj.val($(this).find(".dic").text()); AutoCompletehide(divId); });
    $("#" + divId + " .die span").live("click", function() { AutoCompletehide(divId); isClose = true; isSelecting = true; });    //关闭事件
    //处理偏好设置里面的搜索自动下拉框 2010-2-22 by wells
    function getCookie(autoCookies) {
        var a_all_cookies = document.cookie.split(';');
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false;
        for (i = 0; i < a_all_cookies.length; i++) {
            a_temp_cookie = a_all_cookies[i].split('=');
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
            if (cookie_name == autoCookies) {
                b_cookie_found = true;
                if (a_temp_cookie.length > 1)
                    cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                return cookie_value;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if (!b_cookie_found)
            return null;
    }
    var autoCookie = eval('( ' + getCookie("searchSet") + ') ');
    var autostatus = "";
    if (autoCookie != null) { autostatus = autoCookie.autoComplete; }
    if (autostatus != "close") {
        obj.bind("keyup", function(event) {    //键盘按钮事件,当输入一个字符的时候
            var key = event.keyCode; //键盘输入字符 ,上 38 下 40
            if (key == 13) return;
            if ($.trim(obj.val()).length < 1) isClose = false;
            if (isClose) return; //是否点击过关闭按钮
            if ($.trim(obj.val()).length == 0) { AutoCompletehide(divId); return; }

            if (key == 38) {
                var sIndex = $("#" + divId + " tr").index($(".dib"));
                if (sIndex <= 0) { sIndex = $("#" + divId + "  tr").length - 1; $("#" + divId + "  tr.dib").removeClass("dib"); };
                $("#" + divId + "  tr").eq(sIndex).removeClass("dib");
                $("#" + divId + "  tr").eq(sIndex - 1).addClass("dib");
                obj.val($("#" + divId + "  tr.dib .dic").text()); return;
            }
            if (key == 40) {
                var sIndex = $("#" + divId + " tr").index($(".dib"));
                if (sIndex >= $("#" + divId + "  tr").length - 2) { sIndex = -1; $("#" + divId + "  tr.dib").removeClass("dib"); };
                $("#" + divId + "  tr").eq(sIndex).removeClass("dib");
                $("#" + divId + "  tr").eq(sIndex + 1).addClass("dib");
                obj.val($("#" + divId + "  tr.dib .dic").text()); return;
            }
            //回车跳转 location为目的地址,encodeURIComponent 如果有中文必须添加
            //if (key == 13) { AutoCompletehide(divId); location = "/Search/Job?q=" + encodeURIComponent(obj.val()); return; }
            $.getJSON(uri + encodeURIComponent(obj.val()), function(d) {
                retData = ''; //清空
                if (d.result != false) //如果返回不为空
                {
                    if (typeof (fn) == 'function') { fn(d.result); $("#" + divId).css("visibility", "visible"); return; }
                    $.each(d.data, function(i, item) { retData += '<tr class="dia"><td class="dic">' + item.Text.substring(0, 38) + '</td><td class="did">约有' + item.Count + '条结果</td></tr>'; });
                    $("#" + divId + " > tbody").empty().html(retData + '<tr class="dif"><td style="color: gray; white-space: nowrap;"/><td class="die"><span style="cursor: pointer;">关闭<span></tr>');
                    $("#" + divId).css("visibility", "visible");
                    //修正弹出框在IE6中不能遮罩表单下拉控件的问题
                    if (ie6) {
                        $("#ie6_iframe").css("height", "0");
                        $("#ie6_iframe").css({ 'width': obj.width() + modifiedwidth() + 'px', 'height': +divIdObj.height() + 'px', 'top': obj.height() + 10 + 'px', 'left': relativeLeft() + 'px' });
                    }
                } else {
                    //if (ie6)  $("#ie6_iframe").css("height", "0");
                    return;
                };
            });
            //修正弹出窗口远离文本框的问题(保证有键盘事件的时候修正位置)
            //** $("#" + divId).css({ 'width': obj.width() + 3, 'top': obj.height() + obj.offset().top + 4, 'left': obj.offset().left });
            $("#" + divId).css({ 'width': obj.width() + modifiedwidth() + 'px', 'top': obj.height() + 10 + 'px', 'left': relativeLeft() + 'px' });
        });
    }
    
}//autocomplete初始化;
$(function() {
    if ($('#iptText').length > 0) {
        AutoComplete('iptText', '/Search/AutoComplete?letter=');
    }
    $('#searchForm').submit(function() {
        if ($.trim($('#iptText').val().replace(/[&|%|\?|？|\*|!|~|^|(|)|+|,|。|<|>|"|'|;|:]/)).length < 1) {
            $('#iptText').val('');
            return false;
        }
        var iptText = $('#iptText').val().replace(/[&|%|\?|？|\*|!|~|^|(|)|+|,|。|<|>|"|'|;|:]/g);
        $('#iptText').val(iptText);
        return true;
    });
});
/*
* 随机数
*/
function randomNumber(limit) {
    return Math.floor(Math.random() * limit);
}
/*
*	cookies 操作
*/
// writeCookie("myCookie", "my name", 24);
function writeCookie(name, value, hours,path) {
    var expire = "";
    if (hours != null) {
        expire = new Date((new Date()).getTime() + hours * 3600000);
        expire = "; expires=" + expire.toGMTString() + "; path=" + (path != undefined) ? path : '/' + " ;";
    }
    document.cookie = name + "=" + escape(value) + expire;
}
// alert( readCookie("myCookie") );
function readCookie(name) {
    var cookieValue = "";
    var search = name + "=";
    if (document.cookie.length > 0) {
        var cde = document.cookie;
        offset = document.cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) end = document.cookie.length;
            cookieValue = unescape(document.cookie.substring(offset, end))
        }
    }
    return cookieValue;
}
//删除 cookies
function delCookie(name)//删除cookie
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = readCookie(name);
    if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
//json字符串转换成json对象
function toJson(data) {
    if (data == undefined || data.length < 1) return "";
    return eval('(' + data + ')');
}

/*
* Div Model Dialog
*/
var modalDialogCss ='<style class="dialog" type="text/css">';
modalDialogCss += ' .jqmWindow { display: none; position: fixed; top: 17%; left: 50%; margin-left: -300px; width: 600px; background-color: #EEE; color: #333; border: 1px solid black; padding: 12px; }';
modalDialogCss += ' .jqmOverlay { background-color: #000; }';
modalDialogCss += ' * iframe.jqm { position:absolute; top:0; left:0; z-index:-1;  width: expression(this.parentNode.offsetWidth+"px"); height: expression(this.parentNode.offsetHeight+"px");}';
modalDialogCss += ' * html .jqmWindow { position: absolute;  top: expression((document.documentElement.scrollTop || document.body.scrollTop) + Math.round(17 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + "px");}';
modalDialogCss += ' </style>';
(function($) {
$.fn.jqm = function(o) {
        var p = { overlay: 50,  overlayClass: 'jqmOverlay',            closeClass: 'jqmClose',            trigger: '.jqModal',            ajax: F,            ajaxText: '',            target: F,            modal: F,            toTop: F,            onShow: F,            onHide: F,            onLoad: F
        };
        return this.each(function() {
            if (this._jqm) return H[this._jqm].c = $.extend({}, H[this._jqm].c, o); s++; this._jqm = s;
            H[s] = { c: $.extend(p, $.jqm.params, o), a: F, w: $(this).addClass('jqmID' + s), s: s };
            if (p.trigger) $(this).jqmAddTrigger(p.trigger);
        });
    };

    $.fn.jqmAddClose = function(e) { return hs(this, e, 'jqmHide'); };
    $.fn.jqmAddTrigger = function(e) { return hs(this, e, 'jqmShow'); };
    $.fn.jqmShow = function(t) { return this.each(function() { t = t || window.event; $.jqm.open(this._jqm, t); }); };
    $.fn.jqmHide = function(t) { return this.each(function() { t = t || window.event; $.jqm.close(this._jqm, t) }); };

    $.jqm = {
        hash: {},
        open: function(s, t) {
            var h = H[s], c = h.c, cc = '.' + c.closeClass, z = (parseInt(h.w.css('z-index'))), z = (z > 0) ? z : 3000, o = $('<div></div>').css({ height: '100%', width: '100%', position: 'fixed', left: 0, top: 0, 'z-index': z - 1, opacity: c.overlay / 100 }); if (h.a) return F; h.t = t; h.a = true; h.w.css('z-index', z);
            if (c.modal) { if (!A[0]) L('bind'); A.push(s); }
            else if (c.overlay > 0) h.w.jqmAddClose(o);
            else o = F;

            h.o = (o) ? o.addClass(c.overlayClass).prependTo('body') : F;
            if (ie6) { $('html,body').css({ height: '100%', width: '100%' }); if (o) { o = o.css({ position: 'absolute' })[0]; for (var y in { Top: 1, Left: 1 }) o.style.setExpression(y.toLowerCase(), "(_=(document.documentElement.scroll" + y + " || document.body.scroll" + y + "))+'px'"); } }

            if (c.ajax) {
                var r = c.target || h.w, u = c.ajax, r = (typeof r == 'string') ? $(r, h.w) : $(r), u = (u.substr(0, 1) == '@') ? $(t).attr(u.substring(1)) : u;
                r.html(c.ajaxText).load(u, function() { if (c.onLoad) c.onLoad.call(this, h); if (cc) h.w.jqmAddClose($(cc, h.w)); e(h); });
            }
            else if (cc) h.w.jqmAddClose($(cc, h.w));

            if (c.toTop && h.o) h.w.before('<span id="jqmP' + h.w[0]._jqm + '"></span>').insertAfter(h.o);
            (c.onShow) ? c.onShow(h) : h.w.show(); e(h); return F;
        },
        close: function(s) {
            var h = H[s]; if (!h.a) return F; h.a = F;
            if (A[0]) { A.pop(); if (!A[0]) L('unbind'); }
            if (h.c.toTop && h.o) $('#jqmP' + h.w[0]._jqm).after(h.w).remove();
            if (h.c.onHide) h.c.onHide(h); else { h.w.hide(); if (h.o) h.o.remove(); } return F;
        },
        params: {}
    };
    var s = 0, H = $.jqm.hash, A = [], ie6 = $.browser.msie && ($.browser.version == "6.0"), F = false,
i = $('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({ opacity: 0 }),
e = function(h) { if (ie6) if (h.o) h.o.html('<p style="width:100%;height:100%"/>').prepend(i); else if (!$('iframe.jqm', h.w)[0]) h.w.prepend(i); f(h); },
f = function(h) { try { $(':input:visible', h.w)[0].focus(); } catch (_) { } },
L = function(t) { $()[t]("keypress", m)[t]("keydown", m)[t]("mousedown", m); },
m = function(e) { var h = H[A[A.length - 1]], r = (!$(e.target).parents('.jqmID' + h.s)[0]); if (r) f(h); return !r; },
hs = function(w, t, c) {
    return w.each(function() {
        var s = this._jqm; $(t).each(function() {
            if (!this[c]) { this[c] = []; $(this).click(function() { for (var i in { jqmShow: 1, jqmHide: 1 }) for (var s in this[i]) if (H[this[i][s]]) H[this[i][s]].w[i](this); return F; }); } this[c].push(s);
        });
    });
};
})(jQuery);
$(function () {$('.isDialog').jqm({ modal: true });
});

//弹出对话框方法
function ds(dlgId) {
    var obj = $('#' + dlgId);
    if (obj.length < 1) return;
    if (obj.find('.close').length > 0) { obj.find('.close').bind('click', function() { cd(dlgId) }); }
    
    var sumLength = $(document).width();
    var elemLength = obj.width();
    var offsetDistance = (sumLength / 2) - (elemLength / 2); 
    var offsetHeight = $(document).height() / 2 - obj.height() / 2;
    //获取对象
    obj.css("left", offsetDistance + "px").css({ "position": "absolute", "top": offsetHeight + 'px' })  //样式处理
    $(window).resize(function() { refreshDialogPosition(dlgId); });
    if ($('.dialog').length < 1) obj.before(modalDialogCss);
    obj.jqmShow();
}
//关闭对话框方法
function cd(dlgId,fn) {
    var obj = $('#' + dlgId);
    $(window).unbind();
    if (obj.length == 0) return;
    if (obj.find('.close').length > 0) {obj.find('.close').unbind(); }
    obj.jqmHide();
    if (typeof (fn) == 'function') fn(dlgId);
}
function refreshDialogPosition(dlgId) {
    var obj = $('#' + dlgId);
    if (obj.length < 1) return;
    var sumLength = $(document).width();
    var elemLength = obj.width();
    var offsetDistance = (sumLength / 2) - (elemLength / 2); //颜色忽略掉
    var offsetHeight = ($(document).height() / 2 - obj.height() / 2 - 50);
    obj.css("left", offsetDistance + "px").css({ "position": "absolute", "top": offsetHeight + 'px' })  //样式处理
}

function AddFavorite(sURL, sTitle) {
    try {
        window.external.addFavorite(sURL, sTitle);
    }
    catch (e) {
        try {
            window.sidebar.addPanel(sTitle, sURL, "");
        }
        catch (e) {
            alert("加入收藏失败，请使用Ctrl+D进行添加");
        }
    }
}
function SetHome(obj, vrl) {
    try {
        obj.style.behavior = 'url(#default#homepage)'; obj.setHomePage(vrl);
    }
    catch (e) {
        if (window.netscape) {
            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', vrl);
        }
    }
}

