//返回对象
function jso(_obj){
	if(typeof(_obj) == "string"){
	    return document.getElementById(_obj);
    }else{
	    return _obj;
    }
}

/*****************设置和设置对象的 宽，高，左，上***************/
var w3c=(document.getElementById)? true:false;
var agt=navigator.userAgent.toLowerCase();
var ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1) && (agt.indexOf("omniweb") == -1));
var ie5=(w3c && ie)? true : false;
var ns6=(w3c && (navigator.appName=="Netscape"))? true: false;
var op8=(navigator.userAgent.toLowerCase().indexOf("opera")==-1)? false:true;
var MS = {"Browser":{}};
function GetObjWHLT(obj){
	var objWHLT={left:0,top:0,width:0,height:0};
    var nLt=0;
    var nTp=0;
    var offsetParent = obj;
    while (offsetParent!=null && offsetParent!=document.body){
        nLt+=offsetParent.offsetLeft;
        nTp+=offsetParent.offsetTop;
        if(!ns6){
            parseInt(offsetParent.currentStyle.borderLeftWidth)>0?nLt+=parseInt(offsetParent.currentStyle.borderLeftWidth):"";
            parseInt(offsetParent.currentStyle.borderTopWidth)>0?nTp+=parseInt(offsetParent.currentStyle.borderTopWidth):"";
        }
        offsetParent=offsetParent.offsetParent;
    }
    //alert("ID:"+o.id+"\n\nL:"+nLt+" T:"+nTp+"\nW:"+o.offsetWidth+" H:"+o.offsetHeight);
    objWHLT.left = nLt;
    objWHLT.top = nTp;
    objWHLT.width = obj.offsetWidth;
    objWHLT.height = obj.offsetHeight;
    return objWHLT;
}

function GetSubStringLen(str)
{
    var newStr = new Array();
    var index =0;
    for(var i=0;i<=str.length-1;i++){
        var _str = str.substring(i,i+1);
        var code = escape(str.charAt(i));
        if ((code.length >= 4) && (code < '%uFF60' || code > '%uFF9F')){
            index = index + 2;
        }else{
            index = index + 1;
        }
    }
    return index;
}

Object.extend = function(dest, source, replace) {
	for(var prop in source) {
		if(replace == false && dest[prop] != null) { continue; }
		dest[prop] = source[prop];
	}
	return dest;
};

Object.extend(MS.Browser, {
	isIE: navigator.userAgent.indexOf('MSIE') != -1,
	isFirefox: navigator.userAgent.indexOf('Firefox') != -1,
	isOpera: window.opera != null
}, false);

jQuery.extend(Array.prototype, {
    //特殊方法，不适用于普通数组
    remove: function(item) {
        var array = this.clone();
        this.length = 0;
        for( var i = 0; i < array.length; i++) {
            if (array[i].id != item) this.push(array[i]);
        }
        return this;
    },

    //特殊方法，不适用于普通数组
    has: function(item) {
        for(var i = 0; i < this.length; i++) {
            if (this[i] == item) return true;
            if (typeof item == "object" && this[i].id == item.id) return true;
        }
        return false;
    },

    //特殊方法，不适用于普通数组
    findById: function(id) {
        for (var i = 0; i < this.length; i++) {
            if (this[i].id == id) return this[i];
        }
        return null;
    },

    clear: function() {
        this.length = 0;
        return this;
    },

    clone: function() {
        return [].concat(this);
    }
});

function locConverter(locIDs) {
    var arrLoc = locIDs.split(",");
    var temp = [];
    for (var i = 0; i < arrLoc.length; i++) {
        temp.push(ConverterLoc(arrLoc[i]));
    }
    return temp;
}

function traversal(id, items) {
    var p = items.findById(id);
    if (p != null) {
        return { id: p.id, name: p.name, parObj: null };
    }else {
        var subItems, c;
        for(var i = 0; i < items.length; i++) {
            p = items[i];
            c = p.subItems.findById(id);
            if (c != null) return { id: c.id, name: c.name, parObj: { id: p.id, name: p.name, parObj: null } };
        }
    }
    return null;
}

function dbcToSbc(str) {
    return str.replace(/（/g, "(").replace(/）/g, ")");
}

function getY(el) {
    var y = 0;
    for(var e = el; e; e = e.offsetParent) // Iterate the offsetParents
        y += e.offsetTop;                       // Add up offsetTop values

    // Now loop up through the ancestors of the element, looking for
    // any that have scrollTop set. Subtract these scrolling values from
    // the total offset. However, we must be sure to stop the loop before
    // we reach document.body, or we'll take document scrolling into account
    // and end up converting our offset to window coordinates.
    for(e = el.parentNode; e && e != document.body; e = e.parentNode)
        if (e.scrollTop) y -= e.scrollTop;  // subtract scrollbar values

    // This is the Y coordinate with document-internal scrolling accounted for.
    return y;
}

var PopupSelector = {
    loadSelected: function(type, ref, container) {
        var temp = [];
        var allInds = "";
        var allCats = "";
        var allLocs = "";

        //当前行业
        if (type == "curInd") {
            var selCurIndIDs = ref.split(",");
            this._selItems["curind"].clear();
            allInds = getArray(Industry);
            var indItem;
            for (var i = 0; i < selCurIndIDs.length; i++) {
                indItem = traversal(selCurIndIDs[i], allInds);
                if (indItem != null) {
                    this._selItems["curind"].push(indItem);
                    temp.push(indItem['name']);
                }
            }
        }
        //当前职位类别
        if (type == "curCat") {
            var selCurCatIDs = ref.split(",");
            this._selItems["curcat"].clear();
            allCats = get2DArray(FunType);

            var catItem;
            for (var i = 0; i < selCurCatIDs.length; i++) {
                catItem = traversal(selCurCatIDs[i], allCats);
                if (catItem != null) {
                    this._selItems["curcat"].push(catItem);
                    temp.push(catItem['name']);
                }
            }
        }
        //当前地区
        if (type == "curLoc") {
            var selCurLocIDs = ref.split(",");
            this._selItems["curloc"].clear();
            allLocs = getArray(CityArea);

            var locItem;
            for (var i = 0; i < selCurLocIDs.length; i++) {
                locItem = traversal(selCurLocIDs[i], allLocs);
                if (locItem != null) {
                    this._selItems["curloc"].push(locItem);
                    temp.push(locItem['name']);
                }
            }
        }
        //期望行业
        if (type == "expInd") {
            var selExpIndIDs = ref.split(",");
            this._selItems["ind"].clear();
            allInds = (allInds == "") ? getArray(Industry) : allInds;
            var indExpItem;
            for (var i = 0; i < selExpIndIDs.length; i++) {
                indExpItem = traversal(selExpIndIDs[i], allInds);
                if (indExpItem != null) {
                    this._selItems["ind"].push(indExpItem);
                    temp.push(indExpItem['name']);
                }
            }
        }
        //期望职位类别
        if (type == "expCat") {
            var selExpCatIDs = ref.split(",");
            this._selItems["cat"].clear();
            allCats = (allCats == "") ? get2DArray(FunType) : allCats;
            var catExpItem;
            for (var i = 0; i < selExpCatIDs.length; i++) {
                catExpItem = traversal(selExpCatIDs[i], allCats);
                if (catExpItem != null) {
                    this._selItems["cat"].push(catExpItem);
                    temp.push(catExpItem['name']);
                }
            }
        }
        //期望地区
        if (type == "expLoc") {
            var selExpLocIDs = ref.split(",");
            this._selItems["loc"].clear();
            allLocs = (allLocs == "") ? getArray(CityArea) : allLocs;
            var locExpItem;
            for (var i = 0; i < selExpLocIDs.length; i++) {
                locExpItem = traversal(selExpLocIDs[i], allLocs);
                if (locExpItem != null) {
                    this._selItems["loc"].push(locExpItem);
                    temp.push(locExpItem['name']);
                }
            }
        }

        $("#"+container).val(dbcToSbc(temp.join("+")));
    },

    popup: function(type, ref, valueContainer, single) {
        if (this._box == null) this._box = $("#popupSelector");
        if (this._subBox == null) this._subBox = $("#subItems");
        this._ref = ref;
        this._type = type.toString().toLowerCase();
        this._valueContainer = valueContainer;
        this._curItems = this._selItems[this._type].clone();
        this._single = single;

        this.render();
    },

    render: function() {
        var pslayer = $("#pslayer");
        for (var i = 0; i < this._types.length; i++) {
            pslayer.removeClass(this._style.className.levelOne[this._types[i]]);
        }
        pslayer.addClass(this._style.className.levelOne[this._type]);
        $("#selectingHeader").html(this._gtYourSelected[this._type]);
        $("#psHeader").html(this._gtPopupSelectorHeader[this._type]);

        var html = [];
        var parItems = this.allItems[this._type]();
        var start = 0;
        var end = parItems.length;

        for (var i = start; i < end; i++) {
            var parItem = parItems[i];
            if (parItem.subItems && parItem.subItems.length > 1) {
                html.push("<li onmouseover=\"PopupSelector.showSubItems(");
                html.push(i);
                html.push(", this, true)\" onmouseout=\"PopupSelector.hideSubItems(this)\">");
            }else {
                html.push("<li class=\"nonelay\">");
            }
            html.push("<a href=\"javascript:void(0);\">");
            if (this._type == "ind" || this._type == "curind") {
                html.push("<label for=\"pcbx");
                html.push(parItem.id);
                html.push("\">");
            }
            html.push("<input id=\"pcbx");
            html.push(parItem.id);
            html.push("\" type=\"");
            html.push(this._single ? "radio\" name=\"" + this._type : "checkbox");
            html.push("\" value=\"");
            //            html.push("\" type=\"radio\" value=\"");
            html.push(parItem.id);
            html.push("@");
            html.push(parItem.name);
            html.push("\"");
            if (this._curItems.has({ id: parItem.id, name: parItem.name, parObj: null })){ html.push(" checked");}
            html.push(" onclick=\"PopupSelector.click(this, null)\" />");
            html.push(dbcToSbc(parItem.name));
            if (this._type == "ind" || this._type == "curind") {
                html.push("</label>");
            }
            html.push("</a></li>");
        }
        $("#allItems").html(html.join(""));
        html.length = 0;
        $("#divSelecting").css("display", (this._curItems.length == 0) ? "none" : "block");
        var displayNoSelected = (this._curItems.length == 0) ? "block" : "none";

        if (this._type == "cat") {
			$("#noSelected").css("display", displayNoSelected);
			$("#tips_content").text('请选择您希望从事的职位类别，您最多可以选择5个职位类别。');
        }else if (this._type == "curcat") {
			$("#noSelected").css("display", displayNoSelected);
            $("#tips_content").text('请选择您现在从事的职业。');
        }else if (this._type == "curloc") {
			$("#noSelected").css("display", displayNoSelected);
            $("#tips_content").text('请选择您的现居住地。');
        }else if (this._type == "loc") {
			$("#noSelected").css("display", displayNoSelected);
            $("#tips_content").text('请选择您希望从事工作的地区，您最多可以选择5个城市。');
        }else {
			$("#noSelected").hide();
            $("#tips_content").text('');
        }
        for (var i = 0; i < this._curItems.length; i++) {
            html.push("<li id=\"");
            html.push(this._curItems[i].id);
            html.push("\"><a href=\"javascript:void(0);\" onclick=\"PopupSelector.remove(");
            html.push(this._curItems[i].id);
            html.push(")\">");

            var tmpName = dbcToSbc(this._curItems[i].name);
            if (this._selectedMaxWordLen[this._type] != 0 && GetSubStringLen(tmpName) > this._selectedMaxWordLen[this._type])
                tmpName = GetSubString(tmpName, this._selectedMaxWordLen[this._type] - 3) + "...";

            html.push(tmpName);
            html.push("</a></li>");
        }
        $("#selecting").html(html.join(""));
        if (this._type == "ind" || this._type == "curind") {
            $("#divSelecting").show();
            $("#selecting").hide();
        }else{
			$("#selecting").show();
		}

        $("#shield").width(this._style.width[this._type]).height(this._style.height[this._type]);
        $(this._box)/*.css(pos)*/.show();

        var dvWidth = GetObjWHLT(jso('pslayer')).width;
        var dvHeight = GetObjWHLT(jso('pslayer')).height;
        //var totalWidth = document.body.clientWidth;
        //var totalHeight = document.body.clientHeight;
        var totalWidth = window.screen.width;
        var totalHeight = window.screen.height;

        this._style.left = (totalWidth - dvWidth) / 2; //offset.left;
        this._style.top = (totalHeight - dvHeight) / 2; //offset.top;// + jso("dvMain").scrollTop /*层wrapResumeContent滚动条的top*/;
        var pos = { top: (this._style.top), left: this._style.left };

        $(this._box).css(pos);

        $("#mask").height($(document).height()).show();
    },

    close: function() {
        $("#mask").hide();
        this._ref = null;
        $(this._box).hide();
    },

    OK: function() {
        var temp = [];
        jQuery.each(this._curItems, function() {
            temp.push(this.name);
        });

        $("#"+this._ref).val(dbcToSbc(temp.join("+")));
        this._ref = null;
        this._selItems[this._type] = this._curItems.clone();
        this._curItems.clear();

        var arr1 = [];
        jQuery.each(this._selItems[this._type], function() {
            arr1.push(this.id);
        });

        $("#"+this._valueContainer).val(arr1.join(","));

        $("#selecting").html("");
        $("#mask").hide();
        $(this._box).hide();
    },

    empty: function() {
        $("#selecting").html("");
        $("#allItems input").each(function(i) { this.checked = false; });
        this._curItems.clear();
    },

    click: function(cbx, parObj) {
        if (!this._single && cbx.checked && this._curItems.length == this._maxSize) {
            alert(this._gtMaxLimit);
            cbx.checked = false;
            return;
        }

        var item = { id: cbx.value.split("@")[0], name: cbx.value.split("@")[1], parObj: parObj };
        var selecting = document.getElementById("selecting");
        var selItem = null;
        if (cbx.checked) {
            selItem = document.createElement("li");
            selItem.id = item.id;
            var tmpName = dbcToSbc(item.name);
            if (this._selectedMaxWordLen[this._type] != 0 && GetSubStringLen(tmpName) > this._selectedMaxWordLen[this._type])
                tmpName = GetSubString(tmpName, this._selectedMaxWordLen[this._type] - 3) + "...";
            selItem.innerHTML = "<a href=\"javascript:void(0);\" title=\"" + dbcToSbc(item.name) + "\" onclick=\"PopupSelector.remove(" + item.id + ");\">" + tmpName + "</a>";
            if (!this._single) {
                selecting.appendChild(selItem);
                this._curItems.push(item);
            }
            else {
                selecting.innerHTML = "";
                selecting.appendChild(selItem);
                this._curItems.clear();
                this._curItems.push(item);
            }

        }
        else {
            if (!this._single) {
                selItem = document.getElementById(item.id);
                selecting.removeChild(selItem);
                this._curItems.remove(item.id);
            }
        }
        if (parObj == null) {
            //当点击父类别时，需要取消已选项中属于该父类别的子类别
            var array = this._curItems.clone();
            this._curItems.clear();
            for (var i = 0; i < array.length; i++) {
                if (array[i].parObj != null && array[i].parObj.id == item.id) {
                    selecting.removeChild(document.getElementById(array[i].id));
                } else {
                    this._curItems.push(array[i]);
                }
            }

            var cbxChkd = cbx.checked;
            var subControl;

            var chkList = $("#subItems input");
            for (var i = 0; i < chkList.length; i++) {
                subControl = chkList[i];
                if (!this._single)
                    subControl.checked = cbxChkd;
                subControl.disabled = cbxChkd;
                subControl = null;
            }
            cbx.checked = cbxChkd;
        }
        this.showHideSelecting(this);
    },

    remove: function(id) {
        document.getElementById("selecting").removeChild(document.getElementById(id));
        var pcbx = document.getElementById("pcbx" + id);
        if (pcbx) pcbx.checked = false;
        var array = this._curItems.clone();
        this._curItems.clear();
        for (var i = 0; i < array.length; i++) {
            if (array[i].id != id) this._curItems.push(array[i]);
        }
        this.showHideSelecting(this);
    },

    //private method
    showHideSelecting: function(selector) {
        $("#noSelected").hide();
        if (selector._curItems.length > 0) {
            $("#divSelecting").show();
        }
    },

    showSubItems: function(index, ref, isDelay, ev) {
        var subItems = $("#subItems");
        if (this._hideTimer) clearTimeout(this._hideTimer);
        if (this._showTimer) clearTimeout(this._showTimer);
        if (index == this._lastPopupIndex && subItems.css("display") == "block") {
            $(ref).addClass("layshow");
            return;
        }
        if (!isDelay) loadSubItems(index, ref, this);
        var self = this;
        this._showTimer = setTimeout(function() { loadSubItems(index, ref, self); }, this._delay);

        function loadSubItems(index, ref, self) {
            var parItem = self.allItems[self._type]()[index];
            var offset = $(ref).offset();
            var subleft = offset.left + self._style.offset.levelTwo[self._type].X ;
            if(subleft + 420 > document.documentElement.clientWidth){
                subleft = document.documentElement.clientWidth - 420;
            }
            var pos = { top: offset.top + self._style.offset.levelTwo[self._type].Y, left: subleft };
            var actualSubItemCount = parItem.subItems.length - 1;
            var calItemCount = (actualSubItemCount % 2 == 0) ? actualSubItemCount / 2 : (actualSubItemCount / 2 + 1);
            if (actualSubItemCount <= self._oneColumnLimit[self._type]) calItemCount = actualSubItemCount;
            var subBoxHeight = self._style.lineHeight * parseInt(calItemCount) + self._style.topBottomMargin;
            var winHeight = $(window).height();
            var remainHeight = winHeight - pos.top + document.documentElement.scrollTop;
            if (remainHeight < subBoxHeight) pos.top = pos.top - (subBoxHeight - remainHeight);
            //如果整个IE窗口的高度小于弹出层的高度，则弹出层以对齐顶部显示
            if (subBoxHeight > winHeight) pos.top = document.documentElement.scrollTop;

            var parentChecked;
            if (PopupSelector._single)
                parentChecked = (ref.getElementsByTagName("input")[0].checked == true) ? " disabled " : "";
            else
                parentChecked = (ref.getElementsByTagName("input")[0].checked == true) ? " checked disabled " : "";
            var item = { id: parItem.id, name: parItem.name, parObj: null };
            var html = [];
            html.push("<ol>");
            for (var i = 1; i < parItem.subItems.length; i++) {
                var subItem = parItem.subItems[i];
                subItem.parObj = item;
                html.push("<li>");
                html.push("<a href=\"javascript:void(0);\"><label for=\"scbx");
                html.push(subItem.id);
                html.push("\"><input id=\"scbx");
                html.push(subItem.id);
                //html.push("\" type=\"checkbox\" value=\"");

                html.push("\" type=\"");
                html.push(PopupSelector._single ? "radio\" name=\"" + PopupSelector._type : "checkbox");
                html.push("\" value=\"");

                html.push(subItem.id);
                html.push("@");
                html.push(subItem.name);
                html.push("\"");
                html.push(parentChecked);
                if (self._curItems.has(subItem)) html.push(" checked");
                html.push(" onclick=\"PopupSelector.click(this, { id: ");
                html.push(parItem.id);
                html.push(", name: '");
                html.push(parItem.name);
                html.push("', parObj: null }");
                html.push(")\" />");
                html.push(dbcToSbc(subItem.name));
                html.push("</label></a></li>");
            }
            html.push("</ol>");

            var subBox = $("#subBox");
            for (var i = 0; i < self._types.length; i++) {
                subItems.removeClass(self._style.className.levelTwo1[self._types[i]]);
                subItems.removeClass(self._style.className.levelTwo2[self._types[i]]);
            }
            var levelTwo = (actualSubItemCount > self._oneColumnLimit[self._type]) ? self._style.className.levelTwo2[self._type] : self._style.className.levelTwo1[self._type];
            self._lastPopupIndex = index;
            $("#subItems").hover(function(e) { self.showSubItems(index, ref, true, e); }, function(e) { self.hideSubItems(ref); });
            subBox.html(html.join(""));
            subItems.addClass(levelTwo).css(pos).show();
        }
    },

    hideSubItems: function(ref) {
        $(ref).removeClass("layshow");
        if (this._showTimer) clearTimeout(this._showTimer);
        if (this._hideTimer) clearTimeout(this._hideTimer);
        this._hideTimer = setTimeout(function() { $("#subItems").hide(); }, 100);
    },

    _showTimer: null,
    _hideTimer: null,
    _lastPopupIndex: null,
    _box: null,
    _subbox: null,
    _ref: null,
    _type: null,
    _types: ["cat", "ind", "loc", "curcat", "curind", "curloc"],
    _maxSize: 5,
    _valueContainer: null,
    _single: false,

    //_curItems：在弹出层显示时，用户增加或减少的选项都在这个数组里，当用户清空时，也是清空此数组，
    //当点击确定时，将此数组中的选项复制到_selItems中对应的数组做持久保存，然后清空此数组
    //示例：[{id:xxx, name:xxxx, parObj:null/object ref, isParent:true/false}, .....]
    _curItems: [],
    _selItems: { cat: [], loc: [], ind: [], curcat: [], curind: [], curloc: [] },

    _gtMaxLimit: "对不起,您的已选项已经达到了5项.请减少已选项,再继续选择",
    _gtYourSelected: { cat: "您选择的职位类别是：", ind: "您最多可以选择５个行业类别", loc: "您选择的工作地点是：", curcat: "您选择的职位类别是：", curind: "请选择您现在从事工作的行业：", curloc: "请选择您的现居住地：" },
    _gtPopupSelectorHeader: { cat: "职位类别", ind: "行业类别", loc: "地点", curcat: "职位类别", curind: "行业类别", curloc: "地点" },
    _oneColumnLimit: { cat: 12, loc: 11, curcat: 12, curloc: 11 }, //二级类别显示成一列的最大条目数，超过这个数就要显示成两列
    _selectedMaxWordLen: { cat: 44, loc: 12, curcat: 44, curloc: 12 },
    _delay: 250,
    _style: {
        className: {
            levelOne: { "cat": "lay_wl", "loc": "lay_wls", "ind": "lay_wll", "curcat": "lay_wl", "curind": "lay_wll", "curloc": "lay_wls" },
            //二级类别一列显示的样式
            levelTwo1: { "cat": "lay_wm", "loc": "lay_wss", "ind": "", "curcat": "lay_wm", "curind": "", "curloc": "lay_wss" },
            //二级类别两列显示的样式
            levelTwo2: { "cat": "lay_wl2", "loc": "lay_ws", "ind": "", "curcat": "lay_wl2", "curind": "", "curloc": "lay_ws" }
        },
        left: 0,
        top: 0,
        width: { "cat": 594, "loc": 466, "ind": 746, "curcat": 594, "curind": 746, "curloc": 466 },
        height: { "cat": 526, "loc": 400, "ind": 510, "curcat": 526, "curind": 510, "curloc": 400 },
        lineHeight: 20,
        topBottomMargin: 17,
        offset: {
            levelOne: { X: 0, Y: 20 },
            levelTwo: { "cat": { X: 284, Y: 0 }, "loc": { X: 110, Y: 0 }, "curcat": { X: 284, Y: 0 }, "curloc": { X: 110, Y: 0} }
        }
    },
    allItems: {
        cat: function() { return get2DArray(FunType)},
        ind: function() { return getArray(Industry)},
        loc: function() { return getArray(CityArea)},

        curcat: function() { return get2DArray(FunType)},
        curind: function() { return getArray(Industry)},
        curloc: function() { return getArray(CityArea)}
    }
};

function get2DArray(array) {
	var catArr = new Array();

	for(var idx = 0; idx < array.length; idx++){
		if(array[idx] == undefined){continue;}
		var tmp = new Array();
		tmp['id'] = idx * 100;
		tmp['name'] = array[idx][0];

		var subtmp = new Array();
		for(var i = 1 ; i < array[idx].length; i++){
			if(array[idx][i] == undefined){continue;}
			var temp = new Array();
			temp['id'] = idx * 100 + i;
			temp['name'] = array[idx][i];
			subtmp.push(temp);
		}
		tmp['subItems'] = subtmp;
		catArr.push(tmp);
	}
	return catArr;
}

function getArray(array) {
	var catArr = new Array();

	for(var idx = 0; idx < array.length; idx++){
		if(array[idx] == undefined){continue;}
		var tmp = new Array();
		tmp['id'] = idx ;
		tmp['name'] = array[idx];
		catArr.push(tmp);
	}
	return catArr;
}
/*  |xGv00|3bd89d4c19708a3aca828d2a50ff2316 */