/******************************************************************************
 * CLASS FOR PAGGING FUNCTION
 ******************************************************************************/
var Pagging = {
    
    _pages_list_div : "page_list",
    
    _data : "",
    
    _search_result_template : "template_total_search_result",
    
    _result_note_id : 'result_note',
    
    _content_template : "template_card",

    _not_hzuser_template : "not_hzuser_card",
    
    _content_location : "page_content_list",
    
    _present_page_num : 0,
    
    _begin_page_num : 0,
    
    _end_page_num : 0,
    
    _each_page_items : 21,
    
    _list_size : 8,
    
    _total_count : 0,
    
    _max_page_num : 0,
    
    _show_num : true,

    _show_type : 0,
    
    _search_mynetwork_id : "search_mynetwork_text",
    
    _search_network_id : "search_advance_network_text",
    
    _userid : "",
    
    _my_profile : null,
    
    _content_id : "content",
    
    _my_network_content_id : "my_network_content",
    
    _core_network_content_id : "core_network_content",
    
    _other_network_tip_id : "other_network_tip",
    
    _other_network_tip_template : "template_other_network_tip",
    
    _permission_tip : "template_permission_tip",
    
    _login_user_name : "login_user_name",
    
    _login_hz_link: "login_hz_link",
    
    _search_bar_div : "search_bar_div",
    
    _invite_content_id : "invite_content",
    //shen添加: 显示在邀请页面的外部邀请模版
     _invite_content : "不久前我受邀加入了恒知网, 并开始用恒知来构筑我的职业网络。恒知网是中国高端商务网络社区的创新者和引领者，率先推行实名邀请制。中国数十万专业人士，数百个一流VC、PE、专业组织、协会、和校友会，选择用恒知网拓展人脉、共享资源、发现机会。 " + "\r\n\r\n" +
	 
	 "经过一段时间的试用，我觉得恒知网干净实用，人群很高端，讨论和交流的话题也很有意思。我很看好恒知网的未来发展，在此特别向你发送一份注册邀请，相信你会在恒知网上见到很多熟悉的朋友。 " + "\r\n\r\n" +
	 
	 "参加【与中国创投领袖共进午餐】活动的机会 " + "\r\n\r\n" +

"恒知网将在9月份邀请恒知用户与熊晓鸽、沈南鹏、陈宏等中国创投领袖共进午餐。通过我送给您的注册链接，你也可以申请参加这个恒知网专属的高端活动。" + "\r\n\r\n" ,

    _indexNum:0,
    _initData : null,
    _searchData : null,
    _one_degree_my : "one_degree_my",
    // USED TO INITIALIZE THE FIRST PAGE
    showInit : function( initData ) {
        if (arguments.length > 1) {
            this._userid = arguments[1];
        }
        
        if ( initData.RETURN ) {
            this._initData = initData;
            if (initData.isMyProfile || initData.basicProfile.networkPermission ) {
                if(initData.isMyProfile){
                    this._data = initData.network.contactList;
                }else{
                    this._data = initData.network.userList;
                }
                
                //alert("data="+this._data[17]);
                this._list_size = initData.network.listSize;
                
                this._max_page_num = Math.ceil(initData.network.totalCount / this._each_page_items);
                if ( !initData.isMyProfile ) {
                    //this._pages_list_div ="other_page_list";
                    $(this._my_network_content_id).replace( $(this._core_network_content_id) );
                    // OTHER USER'S NETWORK, SHOW HIS NETWORK
                    this._showOtherNetworkTip( initData.basicProfile.name,this._list_size );
                    if ($( this._search_bar_div ) != undefined) {
                        $( this._search_bar_div ).hide();
                    }
                } 
                this._showPageList( 1 );
                var degreecount = $(this._one_degree_my);
                if(typeof degreecount != "undefined" && degreecount!=null ){
                    degreecount.update(this._list_size);
                }
            } else {
                $(this._my_network_content_id).replace( $(this._core_network_content_id) );
                // OTHER USER'S NETWORK, SHOW HIS NETWORK
                this._showOtherNetworkTip( initData.basicProfile.name,this._list_size );
                $( this._content_location ).replace( $( this._permission_tip ).innerHTML );
                if ($( this._search_bar_div ) != undefined) {
                    $( this._search_bar_div ).hide();
                }
            }
        } else {
            location.href="/network";
        }
    },
    showSearch : function( pageNum,indexData ){
        var showAlert = this._showAlert( pageNum );
        if ( !showAlert ) {
            return;
        }

        if (arguments.length > 1) {
            this._show_type = arguments[1];
        }

        if (this._show_type == 0) {
            this._resetNote();
        }
        this._showSearchPageList(pageNum,indexData);
    },
    // PAGGING FUNCTION, SHOW PAGE OF PAGENUMBER
    show : function ( pageNum ) {
        // IF THE PAGE IS FIRST OR LAST, SHOW ALERT
        var showAlert = this._showAlert( pageNum );
        if ( !showAlert ) {
            return;
        }
        
        if (arguments.length > 1) {
            this._show_type = arguments[1];
        }
        
        if (this._show_type == 0) {
            this._resetNote();            
        }
        this._showPageList(pageNum);       
    // GET REQUEST URL AND PARAMETER BY SHOW TYPE
    //var reqUrl = this._getRequestUrl();
    //var param = this._getRequestParam( pageNum );
        
    // GET DATA FROM SERVER
    //        new Ajax.Request(reqUrl,
    //        {
    //            method : "post",
    //
    //            parameters : param.toQueryString(),
    //
    //            requestHeaders : { Accept : "application/json"},
    //
    //            onSuccess : function ( transport ) {
    //                var json = transport.responseText.evalJSON( true );
    //
    //                if ( json.RETURN ) {
    //                    this._data = json.network.userList;
    //                    this._max_page_num = Math.ceil(json.network.totalCount / this._each_page_items);
    //                    this._list_size = json.network.listSize;
    //                    if (this._show_type == 1 || this._show_type == 2 || this._show_type == 3) {
    //                        this._showResultNote( json.network.totalCount );
    //                    }
    //                    Pagging._showPageList( pageNum );
    //                } else {
    //                    this._showResultNote( 0 );
    //                }
    //            }.bind(this)
    //
    //        });
    },
    
    replaceInviteContent : function ( profile ) {
        this._my_profile = profile;
        this._showHzLink(profile.basicDetailProfile);
        $( this._invite_content_id ).setValue( this._fill_invite_message() );
        $( this._invite_content_id + '2').setValue( this._fill_invite_message() );        
    },
    
    /*************************** PRIVATE METHOD BEGIN *************************/
    _resetNote : function () {
        if ($(this._result_note_id) != undefined) {
            $(this._result_note_id).className = '';
            $(this._result_note_id).update();
        }
    },
    
    _create_link : function(name, id, type){
        var link = new Element("a",{
            "href":"#"
        });
        link.update(name);

        link.observe("click", function () {
            Pagging.show(1, 3, id, type);
        });
        
        return link;
    },
    
    _fill_invite_message : function () {
        var templateData = { 
            my_hz_link : typeof this._my_profile.basicDetailProfile.screenName == "object" ? "" : this._my_profile.basicDetailProfile.screenName
        };
        var template = new Template( this._invite_content );
        return template.evaluate( templateData );
    },    
        
    // GET REQUEST URL
    _getRequestUrl : function () {
        var reqUrl;
        switch ( this._show_type ) {
            case 0 :
                reqUrl = "/Network.do?action=GET_USER_NETWORK";
                break;

            case 1 :
                reqUrl = "/Network.do?action=SEARCH_MY_NETWORK";
                break;

            case 2 : 
                //            case 3 :
                reqUrl = "/Network.do?action=SEARCH_NETWORK";
                break;

            default :
                reqUrl = "/Network.do?action=GET_USER_NETWORK";
                break;                            
        }
          
        return reqUrl;     
    },
    
    // GET REQUEST PARAMETER
    _getRequestParam : function ( pageNum ) {
        var startIndex = (pageNum - 1) * this._each_page_items;
        var params = new Hash();
        
        switch ( this._show_type ) {
            case 0 :
                if (this._userid != "") {                  
                    params.set("userid", this._userid);
                }
                break;
            
            case 1 :
                params.set("search", $( this._search_mynetwork_id ).getValue().replace(/'/g, '"'));
                break;
            
            case 2 : 
                params.set("search", $( this._search_network_id ).getValue().replace(/'/g, '"'));
                break;
                
            default :
                break;                            
        }
        params.set("startIndex", startIndex);
        params.set("maxItemCount", this._each_page_items);
        
        return params;
    },
    
    // SHOW ALERT IF PAGE IS FIRST PAGE OR LAST PAGE
    _showAlert : function ( pageNum ) {
        if (pageNum < 1) {
            return false;
        } else if (this._max_page_num > 0 && pageNum > this._max_page_num) {
            return false;
        } 
        return true;
    },
    
    // SHOW PAGE LIST AND CONTENT OF PAGE NUMBER
    _showPageList : function ( pageNum ) {
        // CLEAR UP PAGE LIST
        $( this._pages_list_div ).update();
        $( this._content_location ).update();
                
        // IF DATA IS EMPTY, DO NOT SHOW PAGE
        if (this._data == "" || this._list_size == 0) {
            return;
        }
        this._present_page_num = pageNum;
        // UPDATA PAGE NUMBER LIST
        this._updatePageNumList();
        // COMPOSE PAGE LIST
        this._composePageList();
        this._showPage( pageNum );        
    },
    _showSearchPageList : function( pageNum , indexData){
        
        // CLEAR UP PAGE LIST
        $( this._pages_list_div ).update();
        $( this._content_location ).update();
        
        // IF DATA IS EMPTY, DO NOT SHOW PAGE
        if (indexData.size() == 0) {
            return;
        }
        this._present_page_num = pageNum;
        // UPDATA PAGE NUMBER LIST
        this._updatePageNumList();
        // COMPOSE PAGE LIST
        this._composePageList("search");

        this._showSearchPage( pageNum,indexData );
    },
    _showSearchPage : function( pageNum ,indexData){
        var pageToBeShow = $('pages' + pageNum);
        pageToBeShow.className = 'curp';

        var j = (pageNum-1)*this._each_page_items;
        if(j>(this._list_size-1))return;
        // WHICH PAGE SHOULD BE SHOW
        if (pageNum <= this._max_page_num) {
            $( this._content_location ).update();
            var showSize = (this._list_size <= this._each_page_items) ? this._list_size : this._each_page_items;//this._list_size;
            for (var i = j; i < (showSize+j); i++) {
                if(i>(this._list_size-1))return;
                new PersonCard( this._trans(indexData[i]) ).show(this._content_template, this._content_location,i, this._initData.isMyProfile);
            }
        }
     
    },
    //xinjun BEGIN
    _search : function(){
        var input =  $F("search_mynetwork_text");
        if(input=="请输入姓名,别名,或公司名"){
            return;
        }
        if( input.trim().length<1){
            this._list_size = (this._initData).network.listSize;
            this._max_page_num = Math.ceil((this._initData).network.totalCount / this._each_page_items);
            this._showPageList( 1 );
            return;
        }
        input = input.toLocaleLowerCase();
        var indexH = this._indexOfHash(input);        
        var indexArr = this._bubbleSort(indexH.values());

        var indexData = new Array();
        for(var j=0;j<indexArr.size();j++){
            indexH.each(function(p) {
                if(p.value==indexArr[j]){
                    indexData[j]=p.key;
                    indexH.unset(p.key+'');
                    throw $break;
                }
                
            });
        }

        this._searchData = indexData;
        this._list_size = indexData.size();
        this._max_page_num = Math.ceil(indexData.size() / this._each_page_items);

        this._showSearchPageList( 1,indexData );

    },
    _indexOfHash : function(input){
        var indexHash = new Hash();//name
        var otherNameIndex = new Hash();
        var companyIndex = new Hash();

        //根据input的内容搜索name,othername,company中包含input内容，得到的hash();
        for(var i=0; i < (this._initData).network.listSize;i++){
            var everyData = null;
            var otherNameData = null;
            var companyData = null;
            if((this._data[i].basicProfile.name)!=null && (this._data[i].basicProfile.name).trim().length>0){
                everyData = ((this._data[i].basicProfile.name).toLocaleLowerCase()).indexOf(input);
                if(everyData!=-1){
                    indexHash.set(i,everyData);
                }
            }
            if(this._transUtil(this._data[i].basicProfile.otherName) != "" && (this._data[i].basicProfile.otherName).trim().length>0){
                otherNameData = ((this._data[i].basicProfile.otherName).toLocaleLowerCase()).indexOf(input);
             
                if(otherNameData != -1){
                    otherNameIndex.set(i,otherNameData);
                }
            }
          
            if(this._transUtil( this._data[i].basicProfile.company )!=""){
          
                companyData = ((this._data[i].basicProfile.company).toLocaleLowerCase()).indexOf(input);
                if(companyData != -1){
                    companyIndex.set(i,companyData);
                }
            }
        }
        //除去与indexHash相同的记录
        var indexArr = this._bubbleSort(indexHash.keys());//indexHash.keys().sort();
        if(indexArr.size()>0){
            for(var j=0;j<indexArr.size();j++){
                otherNameIndex.each(function(z) {
                    if(z.key==indexArr[j]){
                        otherNameIndex.unset(z.key+'');
                        throw $break;
                    }

                });
            }
        }
      
        //得到最大的value值
        var maxArr = this._bubbleSort(indexHash.values());//(indexHash.values()).sort();//sort()是以字符串来比较的,不是以数字来比较的
        var maxValue = maxArr.size()==0 ? 1 : maxArr[maxArr.size()-1];
        //向indexHash中追加 (别名记录)
        var otherArr = this._bubbleSort(otherNameIndex.values());//otherNameIndex.values().sort();//sort()是以字符串来比较的,不是以数字来比较的
        if(otherArr.size()>0){
            for(var t=0;t<otherArr.size();t++){
                otherNameIndex.each(function(q) {
                    if(q.value==otherArr[t]){
                        maxValue += 1;
                        indexHash.set(q.key,maxValue);
                        otherNameIndex.unset(q.key+'');
                        throw $break;
                    }

                });
            }
        }
     
        //删除与indexHash相同的记录
        indexArr = this._bubbleSort(indexHash.keys());
        if(indexArr.size()>0){
            for(var k=0;k<indexArr.size();k++){
                companyIndex.each(function(q) {
                    if(q.key==indexArr[k]){
                        companyIndex.unset(q.key+'');
                        throw $break;
                    }

                });
            }
        }
        //重新取最大值
        maxArr = this._bubbleSort(indexHash.values());
        maxValue = maxArr.size()==0 ? 1 : maxArr[maxArr.size()-1];

        //向indexHash中追加(以company搜索到的记录)
        var companyArr = this._bubbleSort(companyIndex.values());//(companyIndex.values()).sort();
        if(companyArr.size() >0){
            for(var l = 0;l<companyArr.size();l++){
                companyIndex.each(function(t){
                    if(t.value == companyArr[l]){
                        maxValue +=1;
                        indexHash.set(t.key,maxValue);
                        companyIndex.unset(t.key+'');
                    }
                });
            }
        }

        return indexHash;
    },
    _bubbleSort: function(arr){
        var i = 1;
        var n = arr.length;
        var temp = null;
        var exchange = true;
        for(i=1;i<=n;i++){
            exchange= false;
            for(var j=n-1;j >= i;j--)
                if(arr[j]<arr[j-1]){
                    temp=arr[j];
                    arr[j] = arr[j-1];
                    arr[j-1] = temp;
                    exchange=true;
                }
            if(!exchange)
                break;;
        }
        
        return arr;
    },
    //xinjun END
    // SHOW PAGE CONTENT
    _showPage : function ( pageNum ) {
        //$$('div.curp').each(function(item){item.className='';});
        var pageToBeShow = $('page' + pageNum);
        pageToBeShow.className = 'curp';
        
        var j = (pageNum-1)*this._each_page_items;
        if(j>((this._initData).network.listSize)-1)return;
        // WHICH PAGE SHOULD BE SHOW
        if (pageNum <= this._max_page_num) {

            var showSize = (this._list_size <= this._each_page_items) ? this._list_size : this._each_page_items;//this._list_size;
            for (var i = j; i < (showSize+j); i++) {
                if(i>((this._initData).network.listSize)-1)return;
                new PersonCard( this._trans(i)).show(this._content_template, this._content_location,i, this._initData.isMyProfile);
            } 
        }
    }, 
    
    _transUtil : function (data) {
        return typeof data == 'object' ? '' : data;
    },

    _transUtil2 : function(data){
        return typeof data == 'object' ? '未填写' : data;
    },
    
    _getPhotoPath : function ( gender ) {
        var path = null;
        switch (gender) {
            case -1 : 
                path = '/images/man_s.gif';
                break;
            case 0 : 
                path = '/images/women_s.gif';
                break;
            case 1 :
                path = '/images/man_s.gif';
                break;
        }
        return path;
    },
    
    // TRANSFORM DATA TYPE
    _trans : function ( i ) {
        //if(this._data[i]==null)
        //alert("i="+i);
        var showData = {
            contact_id : this._transUtil( this._data[i].basicProfile.id ),
            is_myprofile : this._transUtil( this._data[i].isMyProfile ),
            friend_uid : this._transUtil( this._data[i].basicProfile.id ),
            name : this._transUtil( this._data[i].basicProfile.name ) == "" ? this._transUtil( this._data[i].basicProfile.email) : this._transUtil( this._data[i].basicProfile.name ),
            degree : this._transUtil( this._data[i].degreeWithMe ),
            photo : this._transUtil( this._data[i].basicProfile.photoMedium ) == '' ? 'src="' + this._getPhotoPath( this._data[i].basicProfile.gender ) + '"' : "src='" + this._data[i].basicProfile.photoMedium + "'",
            occupation : this._transUtil( this._data[i].basicProfile.occupation ),
            company : this._transUtil( this._data[i].basicProfile.company ) == "" ? this._transUtil( this._data[i].basicProfile.industry ) : this._data[i].basicProfile.company,
            screen_name : this._transUtil( this._data[i].basicProfile.screenName ),
            other_name : this._transUtil( this._data[i].basicProfile.otherName ) == '' ? '' : '(' + this._data[i].basicProfile.otherName + ')',
            location : this._transUtil( this._data[i].basicProfile.location ),
            motto : this._transUtil( this._data[i].basicProfile.motto ) == '' ? '' : '" ' + this._transUtil( this._data[i].basicProfile.motto ) + ' "',
            degree_one_count : this._transUtil( this._data[i].basicProfile.degree1Count ),
            degree_two_count : this._transUtil( this._data[i].basicProfile.degree2Count ),
            degree_all_count : this._transUtil( this._data[i].basicProfile.degree3Count ),
            notes : this._transUtil( this._data[i].notes ) == '' ? '' : this._data[i].notes == undefined ? '' : TextReplace( this._data[i].notes ),
            network_permission : typeof this._data[i].basicProfile.networkPermission == "object" ? false : this._data[i].basicProfile.networkPermission,
            email : this._transUtil( this._data[i].basicProfile.email)
        };
        return showData;
    },
 
    // CREATE PAGE LIST
    _composePageList : function (search) {
        // FIRST PAGE NAVIGATION
        var firstPage = this._createFirstPage(search);
        $( this._pages_list_div ).appendChild( firstPage );
        
        // PRE PAGE NAVIGATION
        var prePage = this._createPrePage(search);
        $( this._pages_list_div ).appendChild( prePage );
        
        // NAVIGATION BY PAGE NUMBER
        for (var i = this._begin_page_num; i < this._end_page_num + 1; i++) {
            var newPage = null;
            if(search==null){
                newPage = this._createPage( i );
            }else{
                newPage = this._createPage( i,search );
            }
            
            $( this._pages_list_div ).appendChild( newPage );
            if ( !this._show_num ) {
                newPage.hide();
            }
        }
        
        // NEXT PAGE NAVIGATION
        var nextPage = this._createNextPage(search);
        $( this._pages_list_div ).appendChild( nextPage );
        
        // LAST PAGE NAVIGATION
        var lastPage = this._createLastPage(search);
        $( this._pages_list_div ).appendChild( lastPage );
        
    },

    // CREATE EACH PAGE
    _createPage : function ( n,search ) {
        var page = null;
        if(search==null){
            page = new Element("a", {
                "href" : "#",
                "id" : "page" + n
            });
        }else{
            page = new Element("a", {
                "href" : "#",
                "id" : "pages" + n
            });
        }
        
        page.update( n );
        
        page.observe("click", function () {
            if(search==null){
                this.show(n, this._show_type);
            }else{
                this.showSearch(n, this._searchData);
            }
            
        }.bind(this));
        
        return page;        
    },
    
    // CREATE FIRST PAGE
    _createFirstPage : function (search) {
        var firstPage = new Element("a", {
            "href" : "#"
        });
        firstPage.update("首页");
        firstPage.observe("click", function () {
            if(search==null){
                this.show(1, this._show_type);
            }else{
                this.showSearch(1, this._searchData);
            }
            
        }.bind(this));        
        
        return firstPage;
    },
    
    // CREATE PRE PAGE
    _createPrePage : function (search) {
        var prePage = new Element("a", {
            "href" : "#"
        });
        prePage.update("上一页");
        prePage.observe("click", function () {
            if(search==null){
                this.show(this._present_page_num - 1, this._show_type);
            }else{
                this.showSearch(this._present_page_num - 1, this._searchData);
            }
        }.bind(this)); 
        
        return prePage;
    },
    
    // CREATE NEXT PAGE
    _createNextPage : function (search) {
        var nextPage = new Element("a", {
            "href" : "#"
        });
        nextPage.update("下一页");
        nextPage.observe("click", function () {            
            if(search==null){
                this.show(this._present_page_num + 1, this._show_type);
            }else{
                this.showSearch(this._present_page_num + 1, this._searchData);
            }
        }.bind(this));        

        return nextPage;
    },
    
    // CREATE LAST PAGE
    _createLastPage : function (search) {
        var lastPage = new Element("a", {
            "href" : "#"
        });
        lastPage.update("末页");
        lastPage.observe("click", function () {           
            if(search==null){
                this.show(this._max_page_num, this._show_type);
            }else{
                this.showSearch(this._max_page_num, this._searchData);
            }
        }.bind(this));        
        
        return lastPage;
    },
    
    // UPDATE PAGE NUMBER LIST BY CONDITIONS
    _updatePageNumList : function () {

        // UPDATE PAGE NUMBER LIST IF PRESENT PAGE NUMBER IS FIRST PAGE OR LAST PAGE
        if (this._present_page_num == 1) {
            this._begin_page_num = 1;            
            if (this._max_page_num > 10) {
                this._end_page_num = 10;
            } else if (this._max_page_num > 0) {
                this._end_page_num = this._max_page_num;
            }
        } else if (this._present_page_num == this._max_page_num) {
            this._end_page_num = this._max_page_num;
            if (this._max_page_num > 10) {
                this._begin_page_num = this._max_page_num - 10 + 1;
            } else {
                this._begin_page_num = 1;
            }
        } else {        
            // THE GAP OF PRESENT PAGE NUMBER AND BEGIN PAGE NUMBER
            var stepLen = this._present_page_num - this._begin_page_num;
            
            // IF PAGE NUMBER GAP LARGER THAN 2 AND END PAGE IS NOT MAX PAGE, MOVE RIGHT THE WHOLE PAGE NUMBER LIST
            if ((stepLen > 2) && (this._end_page_num != this._max_page_num)) {

                if (this._present_page_num + 7 > this._max_page_num) {
                    this._end_page_num = this._max_page_num;
                    this._begin_page_num = this._end_page_num - 9;
                } else {
                    this._end_page_num = this._present_page_num + 7;
                    this._begin_page_num = this._end_page_num - 9;
                }

            // IF PRESENT PAGE'S NUMBER MINUS BEGIN PAGE'S NUMBER LESS THAN 2 AND BEGIN PAGE NUMBER IS NOT 1
            // MOVE LEFT THE PAGE NUMBER LIST
            } else if ((stepLen < 2) && (this._begin_page_num != 1)) {

                if (this._present_page_num - 2 < 1) {
                    this._begin_page_num = 1;
                    this._end_page_num = this._begin_page_num + 9;
                } else {
                    this._begin_page_num = this._present_page_num - 2;
                    this._end_page_num = this._begin_page_num + 9;
                }

            } // END OF "else if ((stepLen < 2) && (this._begin_page_num != 1))"
        }
    },
    
    _showResultNote : function ( resultData ) {
        // CLEAR UP THE RESULT NOTE DIV
        $( this._result_note_id ).update();
        // TRANSFORM DATA TYPE
        var total_result_note = { 
            total_count : resultData
        };
        // GET TEMPLATE HTML
        var templateHtml = $( this._search_result_template ).innerHTML.templateDecode();
        // CREATE AND FILL TEMPLATE
        var template = new Template( templateHtml );
        var filledTemplate = template.evaluate( total_result_note );
        // SHOW RESULT NOTE
        $( this._result_note_id ).insert( filledTemplate ); 
    },
    
    _showOtherNetworkTip : function ( name ,size) {
        // CLEAR UP THE RESULT NOTE DIV
        $( this._other_network_tip_id ).update();
        // TRANSFORM DATA TYPE
        var profileName = {
            profile_name : name,
            one_degree_size : size
        };
        // GET TEMPLATE HTML
        var templateHtml = $( this._other_network_tip_template ).innerHTML.templateDecode();
        // CREATE AND FILL TEMPLATE
        var template = new Template( templateHtml );
        var filledTemplate = template.evaluate( profileName );
        // SHOW RESULT NOTE
        $( this._other_network_tip_id ).insert( filledTemplate ); 
    },
    
    _showHzLink : function ( my_profile ) {
        // TRANSFORM DATA TYPE
        var screenName = {
            login_screen_name : my_profile.screenName,
            login_user_name : my_profile.name
        };
        // GET TEMPLATE HTML
        var templateHtml = $( this._login_hz_link ).innerHTML.templateDecode();
        // CREATE AND FILL TEMPLATE
        var template = new Template( templateHtml );
        var fillData = template.evaluate( screenName );
        $( this._login_hz_link ).update( fillData );
        
        var templateHtml2 = $( this._login_hz_link + '2' ).innerHTML.templateDecode();
        var template2 = new Template( templateHtml2 );
        var fillData2 = template2.evaluate( screenName );
        $( this._login_hz_link + '2').update( fillData2 );
    }

/*********************** PRIVATE METHOD END *******************************/
};

/******************************************************************************
 * CLASS FOR SHOW PERSON CARD
 ******************************************************************************/
var PersonCard = Class.create({
    _not_hzuser_template : "not_hzuser_card",
    
    initialize : function (personInfo) {
        this._personInfo = personInfo;         // DATA TO BE SHOWED
        this._location = "";                   // LOCATION WHERE PERSON CARD TO BE SHOWED
        this._template = "";                   // THE TEMPLATE OF PERSON CARD
        this._to_degree = 'to_degree' + personInfo.screen_name;
        this._show_degree = true;
        this._link_network = 'link' + personInfo.screen_name;
        this._is_my_contacts = true;
    },

    // SHOW PERSON CARD CONTENT
    // PARAM1: ID OF TEMPLATE PERSON CARD
    // PARAM2: LOCATION OF PERSON CARD TO DISPLAY
    show : function (personCardTemplate, displayLocation,index, isMyProfile) {
        if(this._personInfo.screen_name == ""){
            this._template = $(this._not_hzuser_template);
        }else{
            this._template = personCardTemplate;
        }
        this._is_my_contacts = isMyProfile;
        this._location = displayLocation;
        
        var personCard = this._createPersonCard(index);    // CREATE A PERSON CARD
        $( this._location ).insert( personCard );      // INSERT THE PERSON CARD TO LOCATION
        //if ( !this._show_degree ) {
        //$( this._to_degree ).replace('');
        //}
        if (this._personInfo.degree == 1) {
            new FriendNotes( this._personInfo ).show();
        }
        //if (!this._personInfo.is_myprofile && this._personInfo.network_permission != undefined && !this._personInfo.network_permission ) {
        //$( this._link_network ).removeAttribute('href');
        //}
        if (this._personInfo.is_myprofile) {
            var link1 = $('profile1' + this._personInfo.screen_name).readAttribute('href');
            $('profile1' + this._personInfo.screen_name).writeAttribute('href', link1.replace(/profile/g, "profile1"));
            var link2 = $('profile2' + this._personInfo.screen_name).readAttribute('href');
            $('profile2' + this._personInfo.screen_name).writeAttribute('href', link2.replace(/profile/g, "profile1"));
        }
    },
    
    /********************** private method begin ******************************/
    
    _createPersonCard : function (index) {
        //alert("index="+index);
        var listCass = " FloatLeft";
        if((index+1)%3==2)
            listCass = " FloatCenter";
        if((index+1)%3==0)
            listCass = " FloatRight";

        if(this._is_my_contacts){
            listCass = "FloatLeft";
            if((index+1)%3==2)
                listCass = "FloatCenterOne";
            if((index+1)%3==0)
                listCass = "FloatRight";
        }

        var personCard = new Element("div", {
            "class" : listCass
        });
        personCard.insert( this._fillPersonCardTemplate() );
        return personCard;
    },

    // FILL PERSON CARD TEMPLATE
    _fillPersonCardTemplate : function () {
        //create template
        var personCardTemplate = this._createPersonCardTemplate();
        var fillResult = personCardTemplate.evaluate( this._personInfo );
        
        if (this._personInfo.degree == undefined || this._personInfo.degree == 0) {
            this._show_degree = false;
        }
        
        return fillResult;
    },
    
    /* 
     * CREATE PERSON CARD TEMPLATE
     */
    _createPersonCardTemplate : function () {
        var personCardHtml = $( this._template ).innerHTML.templateDecode();
        var personCardTemplate = new Template( personCardHtml );
        
        return personCardTemplate;
    }
/************************* PRIVATE METHOD END *****************************/
});

var FriendNotes = Class.create({
    
    initialize : function ( data ) {
        if (arguments.length == 0) {
            return;
        }
        
        this._data = data;
        this._friend_uid = data.friend_uid;
        //this._friend_note_show_div = 'friend_note_show_div' + data.screen_name;
        this._template_friend_note_div = 'template_friend_note_div';
        //this._template_friend_note_edit_div = 'template_friend_note_edit_div';
        //this._friend_note_div = 'friend_note' + data.screen_name;
        //this._textarea_id = 'textarea_id' + data.screen_name;
        //this._save_note_button_id = 'save_note_button' + data.screen_name;
        //this._discard_note_button_id = 'discard_note_button' + data.screen_name;
        this._text = '';
        this._note_tip_text = '<span style="color:#999999">添加备忘</span>';
    },
    
    show : function () {       
        //$( this._friend_note_show_div ).update( $(this._template_friend_note_div ).innerHTML );
        this._fill();
    //this._text = this._data.notes;
    //if (this._data.notes == "") {
    //    $( this._friend_note_div ).innerHTML = this._note_tip_text;
    // }
    },
    
    _edit : function () {
        //$( this._friend_note_show_div ).update( $( this._template_friend_note_edit_div ).innerHTML );
        this._fill();
        
    //$( this._textarea_id ).setValue( HtmlReplace( this._text ) );
    },
    
    _submit : function () {
        
        var reqUrl = "/Network.do?action=UPDATE_NOTES";
        //this._text = $F( this._textarea_id );
        //var param = "friend_uid=" + this._friend_uid + "&notes=" + $F( this._textarea_id );
        
        
        new Ajax.Request(reqUrl,
        {
            method : "post",
            
            parameters : {
                "friend_uid" : this._friend_uid,
                "notes" : $F( this._textarea_id )
            },
            
            requestHeaders : { 
                Accept : "application/json"
            },
            
            onSuccess : function ( transport ) {
                var json = transport.responseText.evalJSON( true );
                if ( json.RETURN ) {
                    //$( this._friend_note_show_div ).update( $( this._template_friend_note_div ).innerHTML );
                    this._fill();
                //$( this._friend_note_div ).innerHTML = (this._text == '' ? this._note_tip_text : TextReplace( this._text ));
                }
            }.bind(this)
            
        });        
        
    },
    
    _discard : function () {
        //$( this._friend_note_show_div ).update( $( this._template_friend_note_div ).innerHTML );
        this._fill();
    //$( this._friend_note_div ).innerHTML = (this._text == undefined || this._text == '' ? this._note_tip_text : TextReplace( this._text ));
    },
    
    _fill : function () {
    // GET TEMPLATE HTML
    //var templateHtml = $( this._friend_note_show_div ).innerHTML.templateDecode();
    // CREATE AND FILL TEMPLATE
    //var template = new Template( templateHtml );
    //var filledTemplate = template.evaluate( this._data );
    // SHOW RESULT NOTE
    //$( this._friend_note_show_div ).update( filledTemplate );
        
    //if ($( this._friend_note_div ) != undefined) {
    //   $( this._friend_note_div ).observe('click', function () {
    //     this._edit();
    // }.bind( this ));
    //}
        
    //        if ($( this._save_note_button_id ) != undefined) {
    //            $( this._save_note_button_id ).observe('click', function () {
    //                this._submit();
    //            }.bind( this ));
    //        }

    //        if ($( this._discard_note_button_id ) != undefined) {
    //            $( this._discard_note_button_id ).observe('click', function () {
    //                this._discard();
    //            }.bind( this ));
    //        }
    }
})
/******************************************************************************
 * SEARCH IN MY NETWORK, SHOW MY CONTACT LIST ONLY
 ******************************************************************************/
var SearchMyNetworkAjax = {
    
    _search_text_id : 'search_mynetwork_text',
    
    _msg_id : 'search_msg',
    
    submit : function() {
        if ($('TabbedPanels1') != undefined) {
            TabbedPanels1.showPanel(0);
        }
        // VALIDATE FORM
        if( !this._validate() ) {
            return;
        }
        this._resetMsg();
        Pagging.show(1, 1);
    },
    
    keydown : function() {
        $( this._search_text_id ).observe('keydown', function( event ) {
            this._resetMsg();
            if (event.keyCode == Event.KEY_RETURN) {
                this.submit();
            }
        }.bind( this ));        
    },
    
    _resetMsg : function () {




        $(this._msg_id).className = '';
        $(this._msg_id).update();        
    },
    
    _validate : function() {
        if( !$( this._search_text_id ).present() ) {
            show_error_msg(this._msg_id, '请输入搜索姓名');
            $( this._search_text_id ).focus();
            return false;
        }
        return true;
    }    
}

/******************************************************************************
 * SEARCH IN GLOBAL NETWORK, REDIRECT LOCATION TO SEARCH.JSP
 *******************************************************************************/
var SearchNetworkAjax = {
    
    _search_url : "/search.jsp?search_text=",
    
    _search_login_text_id : "search_login_network_text",
    
    _search_unlogin_text_id : "search_unlogin_network_text",
    
    _search_text_id : "",
    
    _msg_id : "show_msg",
    
    submit : function() {
        this._setSearchTextId();
        
        if ( !this._validate() ) {
            return;
        }

        location.href = encodeURI( this._search_url + $F( this._search_text_id ) );
    },
    
    keydown : function() {
        this._setSearchTextId();
        
        $( this._search_text_id ).observe('keydown', function( event ) {
            if (event.keyCode == Event.KEY_RETURN) {
                this.submit();
            }
        }.bind( this ));
    },
   
    _setSearchTextId : function () {
        if ($(this._search_login_text_id) == null) {
            this._search_text_id = this._search_unlogin_text_id;
        } else {
            this._search_text_id = this._search_login_text_id;
        }               
    },
   
    _validate : function () {
        if ( !$( this._search_text_id ).present() ) {
            //            show_error_msg(this._msg_id, '请输入搜索姓名');
            $( this._search_text_id ).focus();
            return false;
        }
        return true;
    }
}

/******************************************************************************
 * SEARCH IN GLOBAL, SHOW ALL HENGZHI USER FIT TO SEARCH CONDITION
 ******************************************************************************/
var SearchAdvanceNetworkAjax = {
    
    _search_url : "/search.jsp",
    
    _search_text_id : "search_advance_network_text",
    
    _search_button_id : "search_advance_network_button",
    
    _re_search_link_id : "re_search_link",
    
    _msg_id : "show_msg",
    
    submit : function() {
        if ( !this._validate() ) {
            return;
        }
        Pagging.show(1, 2);
    },

    keydown : function() {
        $( this._search_text_id ).observe('keydown', function( event ) {
            if (event.keyCode == Event.KEY_RETURN) {
                this.submit();
            }
        }.bind( this ));        
    },
    
    hide : function ( searchText ) {
        $( this._search_text_id ).setValue( searchText );
        $( this._search_text_id ).hide();
        $( this._search_button_id ).hide();
    //        $( this._re_search_link_id ).show();
    },
    
    show : function () {
        $( this._search_text_id ).show();
        $( this._search_button_id ).show();
        $( this._re_search_link_id ).hide();        
    },
    
    _validate : function () {
        if ( !$( this._search_text_id ).present() ) {
            //            show_error_msg(this._msg_id, '请输入搜索姓名');
            $( this._search_text_id ).focus();
            return false;
        }
        return true;
    }
}

/******************************************************************************
 *  SEND INVITE TO SERVER
 ******************************************************************************/
var SendInvite = {
     
    _ajax_url : "/Network.do?action=SEND_EXT_INVITATION",

    _invite_other_name : "invite_other_name",
     
    _invite_name : "invite_name",
     
    _invite_email : "invite_email",

    _invite_company : "invite_company",

    _invite_occupation : "invite_occupation",

    _invite_fixphone : "invite_fixphone",

    _invite_phone : "invite_phone",
     
    _invite_name_email_count : 1,
    
    _invite_subject : "恒知网 | 递名片",
     
    _invite_content : "invite_content",
     
    _invite_name_email_array : "",
     
    _msg : "wrong_msg",
     
    _send_invite_button_id : "send_invite_button",
    
    _error_arrow_img : 'error_arrow_img',
     
    submit : function () {
        if ( !this._validate() ) {
            //show_error_msg(this._msg, "邮箱地址格式不正确");
            return;
        }
                
        //var params = "nameEmailPairs=" + this._invite_name_email_array.toJSON() + "&subject=" + this._invite_subject + "&message=" + $F( this._invite_content );
        var params = new Hash();
        params.set("nameEmailPairs", this._invite_name_email_array.toJSON());
        params.set("subject", this._invite_subject);
        params.set("message", $F( this._invite_content ));
        
        new Ajax.Request(this._ajax_url,
        {
            method : "post",
            parameters : params,
            requestHeaders : {
                Accept : "application/json"
            },
            onCreate: function(){
                this._onCreate();
            }.bind( this ),
             
            onSuccess : function (transport) {
                var json = transport.responseText.evalJSON( true );
                if ( json.RETURN ) {
                    if ( this._clearSuccessItems() ) {
                        show_success_msg(this._msg, "邀请发送成功");
                    } else {
                        show_error_msg(this._msg, "下列邀请发送失败");
                    }
                } else {                    
                    show_error_msg(this._msg, json.MESSAGE);
                //                    for (var i = 0; i < json.resultList.length; i++) {
                //                        var index = this._getErrorIndex(json.resultList[i].name, json.resultList[i].email);
                //                        if (index != -1 && json.resultList[i].RETURN ) {
                //                                if(!json.resultList[i].ISBREAK){
                //                                    $(this._invite_name + index).setValue('');
                //                                    $(this._invite_email + index).setValue('');
                //                                    $(this._error_arrow_img + index).hide();
                //                                }
                //
                //                        } else {
                //                            $(this._error_arrow_img + index).show();
                //                        }
                //                    }
                }
            }.bind( this ),
             
            onComplete : function () {
                this._onComplete();
            }.bind( this )
        });         
    },
    
    _getErrorIndex : function (name, email) {
        for (var i = 0; i < this._invite_name_email_count; i++) {
            if ($F(this._invite_name + i) == name && $F(this._invite_email + i) == email) {
                return i;
            }
        }
        
        return -1;
    },
 
    _validate : function () {
        //this._clearArrowImg();
        if ( !this._validateNameEmails() ) {
            show_error_msg(this._msg, "请输入正确的姓名和电子邮件地址");
            return false;             
        }
        if ( !$(this._invite_content).present() ) {
            show_error_msg(this._msg, "请输入信体");
            $( this._invite_content ).focus();
            return false;
        }
        return true;
    },
    // VALIDATE AND GET NAME & EMAIL PAIR
    _validateNameEmails : function () {
        this._invite_name_email_array = new Array();
        var bSubmit = true;
        var valideSize = 0;
        for (var i = 0; i < this._invite_name_email_count; i++) {
            if ( this._validateNameEmailPair(this._invite_name + i, this._invite_email + i) ) {
                if ( !checkEmail( $F(this._invite_email + i) ) ) {
                    //$(this._error_arrow_img + i).show();
                    bSubmit = false;
                    continue;
                }
                var nameEmailPair = {
                    name : $F(this._invite_name + i).strip(),
                    otherName : $F(this._invite_other_name + i).strip(),
                    email : $F(this._invite_email + i).strip(),
                    company : $F(this._invite_company + i).strip(),
                    occupation : $F(this._invite_occupation + i).strip(),
                    fixphone : $F(this._invite_fixphone + i).strip(),
                    phone : $F(this._invite_phone + i).strip()
                };
                this._invite_name_email_array[i] = nameEmailPair;
                valideSize++;
            } else if (this._partiallyInput( i )) {
                //$(this._error_arrow_img + i).show();
                bSubmit = false;
            }
        }
        if (!bSubmit || valideSize <= 0) {
            return false;
        }
        return true;
    },
    // VALIDATE NAME & EMAIL PAIR
    _validateNameEmailPair : function (name, email) {
        if ($( name ).present() && $( email ).present()) {
            return true;
        }
        return false;
    },
    
    _clearSuccessItems : function () {
        var result = true;
        for (var i = 0; i < this._invite_name_email_count; i++) {
            if ( this._validateNameEmailPair(this._invite_name + i, this._invite_email + i) ) {
                $(this._invite_name + i).setValue('');
                $(this._invite_other_name + i).setValue('');
                $(this._invite_email + i).setValue('');
                $(this._invite_company + i).setValue('');
                $(this._invite_occupation + i).setValue('');
                $(this._invite_fixphone + i).setValue('');
                $(this._invite_phone + i).setValue('');
            //$(this._error_arrow_img + i).hide();
            } else if (this._partiallyInput( i )) {
                result = false;
            }
        }
        return result;
    },
    
    _partiallyInput : function ( i ) {
        return $(this._invite_name + i).present() || $(this._invite_email + i).present();
    },
    
    _clearUp : function () {
        for (var i = 0; i < this._invite_name_email_count; i++) {
            $(this._invite_name + i).setValue('');
            $(this._invite_other_name + i).setValue('');
            $(this._invite_email + i).setValue('');
            $(this._invite_company + i).setValue('');
            $(this._invite_occupation + i).setValue('');
            $(this._invite_fixphone + i).setValue('');
            $(this._invite_phone + i).setValue('');
        //$(this._error_arrow_img + i).hide();
        }
    },
    
    _clearArrowImg : function () {
        for (var i = 0; i < this._invite_name_email_count; i++) {
        //$(this._error_arrow_img + i).hide();
        }        
    },
     
    _onCreate : function () {
        $( this._send_invite_button_id ).disable();
        show_send_msg(this._msg, "邀请发送中, 请稍候。。。");
    },
     
    _onComplete : function () {
        $( this._send_invite_button_id ).enable();
    },
    
    // ONLY USED BY TAB CHANGE
    resetMsg : function () {
        if ($( this._msg ) != undefined) {
            $( this._msg ).className = "";
            $( this._msg ).update();
        }
        this._clearUp();
    }    
}

var INVITE = {
    
    MY_PROFILE : null,
    
    TO_USER_PROFILE : null,
    
    init : function (my_profile, to_user_profile) {
        this.MY_PROFILE = my_profile;
        this.TO_USER_PROFILE = to_user_profile;
    }
}

var ExtInvite = {
    
    _ajax_url : "/Network.do?action=GET_SEND_EXT_INVITATION",
    
    _invite_list_tbody : 'invite_list',
    
    _each_page_items : 1000,
    
    _data : null,
    
    show_ext_invite_list : function (data) {
        this._data = data;
        $( this._invite_list_tbody ).update();
        var bgcolor = null;
        for (var i = 0; i < this._data.length; i++) {
            if (i % 2 == 0) {
                bgcolor = '#F4F7F9';
            } else {
                bgcolor = '#FFFFFF';
            }
            $( this._invite_list_tbody ).insert( this._fill_ext_invite_item(this._trans( this._data[i] ), bgcolor) );
        }
    },
    
    _fill_ext_invite_item : function (data, bgcolor) {
        var tr = new Element('tr', {
            'bgcolor' : bgcolor
        });
        var td1 = new Element('td');
        td1.update( data.to_name );
        tr.appendChild( td1 );
        var td2 = new Element('td');
        td2.update( data.to_email );
        tr.appendChild( td2 );
        var td3 = new Element('td', {
            'class' : 'sortcol',
            'nowrap' : 'nowrap'
        });
        td3.update( data.create_time );
        tr.appendChild( td3 );
        return tr;
    },
    
    _trans : function ( data ) {
        var trans = {
            create_time : this._date(data.basicInfo.createDate),
            to_name : data.basicInfo.toName,
            to_email : data.basicInfo.toEmail
        }
        return trans;
    },
    
    _date : function ( dateString ) {
        var date = new Date( dateString );
        var year = date.getFullYear();
        var month = date.getMonth();
        month++;
        var day = date.getDate();
        return month + '月' + day + '日';
    }    
    
}

var InnerInvite = {
    
    _invite_show_div : 'invite_show_div',
    
    _template_send_inbox : 'template_send_inbox',
    
    _template_recv_inbox : 'template_recv_inbox',
    
    _template_compose_invite : 'template_compose_invite',
    
    init : function () {
        var url = location.href;
        if ( url.include('#send') ) {
            $( this._invite_show_div ).update($( this._template_send_inbox ).innerHTML);
            ViewInviteList.show(1, 0);
        } else if ( url.include('#recv') ) {
            $( this._invite_show_div ).update($( this._template_recv_inbox ).innerHTML);
            ViewInviteList.show(1, 1);
        } else if ( url.include('#compose') ) {
            $( this._invite_show_div ).update($( this._template_compose_invite ).innerHTML);
            SendInnerInvite.init(INVITE.MY_PROFILE, INVITE.TO_USER_PROFILE);            
        } else {
            $( this._invite_show_div ).update($( this._template_compose_invite ).innerHTML);
            SendInnerInvite.init(INVITE.MY_PROFILE, INVITE.TO_USER_PROFILE);            
        }        
        
    }
}

var SendInnerInvite = {
    
    _ajax_url : "/Network.do?action=SEND_INNER_INVITATION",
    
    _invite_show_div : 'invite_show_div',
     
    _invite_name : "invite_name",
    
    _invite_name_obj : null,
     
    _invite_subject : "invite_subject",
    
    _invite_subject_obj : null,
    
    _invite_subject_default_1 : "恒知网 | ",
    
    _invite_subject_default_2 : " 递名片",
     
    _invite_message : "invite_message",
    
    _invite_message_obj : null,
     
    _send_invite_button_id : "send_invite_button",
    
    _send_invite_button_obj : null,
    
    _discard_invite_button_id : 'discard_invite_button',
    
    _discard_invite_button_obj : null,
    
    _login_user_name : "login_user_name",
    
    _login_user_name_obj : null,

    _header_user_name : "header_user_name",
    //shen添加: 发送内部邀请时的信件内容模版，目前此段应该属于冗余代码
    _template_invite_message : '#{to_name} 你好,\r\n\r\n希望能与你互换名片.\r\n\r\n我的恒知名片是www.hengzhi.cc/#{my_hz_link}\r\n\r\n此致,\r\n\r\n#{from_name}',
    
    _my_profile : null,
    
    _to_user_profile : null,
    
    init : function (my_profile, to_user_profile) {
        this._initObj();
        $('compose_invite_ulli').hide();
        if (my_profile == '' || to_user_profile == '') {
            return;
        }
        if (my_profile.basicDetailProfile.screenName == to_user_profile.basicProfile.screenName || to_user_profile.degreeWithMe == 1) {
            ViewInviteList.gotoPage( 1 );
            return;
        }
        $('compose_invite_ulli').show();
        ViewInviteList.lightUl( 2 );
        this._my_profile = my_profile;
        this._to_user_profile = to_user_profile;
        this._invite_subject_obj.setValue(this._invite_subject_default_1 + my_profile.basicDetailProfile.name + this._invite_subject_default_2);
        this._invite_name_obj.setValue( to_user_profile.basicProfile.name );
        this._invite_name_obj.disable();
        this._login_user_name_obj.setValue( my_profile.basicDetailProfile.name );
        this._login_user_name_obj.disable();
        this._invite_message_obj.setValue( this._fill_invite_message() );
    },
    
    _initObj : function () {
        this._invite_subject_obj = $( this._invite_show_div ).select('[id='+ this._invite_subject + ']')[0];
        this._invite_name_obj = $( this._invite_show_div ).select('[id='+ this._invite_name + ']')[0];
        this._login_user_name_obj = $( this._invite_show_div ).select('[id='+ this._login_user_name + ']')[0];
        this._invite_message_obj = $( this._invite_show_div ).select('[id='+ this._invite_message + ']')[0];
        this._send_invite_button_obj = $( this._invite_show_div ).select('[id='+ this._send_invite_button_id + ']')[0];
        this._discard_invite_button_obj = $( this._invite_show_div ).select('[id='+ this._discard_invite_button_id + ']')[0];
    },
    
    submit : function () {
        if ( !this._validate() ) {
            return;
        }
        
        var params = new Hash();
        params.set("userid", this._to_user_profile.basicProfile.screenName);
        params.set("subject", this._invite_subject_obj.getValue());
        params.set("message", this._invite_message_obj.getValue());
        
        new Ajax.Request(this._ajax_url,
        {
            method : "post",
            parameters : params.toQueryString(),
            requestHeaders : {
                Accept : "application/json"
            },
            onCreate: function(){
                this._onCreate();
            }.bind( this ),
             
            onSuccess : function (transport) {
                var json = transport.responseText.evalJSON( true );
                if ( json.RETURN ) {
                    this._showMsg($( this._invite_show_div ), 0, "邀请发送成功");
                } else {
                    this._showMsg($( this._invite_show_div ), 1, json.MESSAGE);
                }
            }.bind( this ),
             
            onComplete : function () {
                this._onComplete();
            }.bind( this )
        });        
    },
    
    discard : function () {
        ViewInviteList.gotoPage( 1 );
    },
    
    _showMsg : function (obj, type, msg) {
        var msgElement = null;
        if ($('msg') == undefined) {
            msgElement = new Element('div', {
                'id' : 'msg',
                'width':'542px',
                'height':'25px',
                'margin':'0px auto'
            });
        } else {
            msgElement = $('msg');
        }
        switch (type) {
            case 0 :
                msgElement.className = 'ok_message';
                break;
            case 1 :
                msgElement.className = 'wrong_message';
                break;
            case 2 :
                msgElement.className = 'sent_message';
                break;
        }
        msgElement.update(msg);
        obj.insert( {
            before:msgElement
        } );
    },
    
    _validate : function () {
        if ( !this._invite_subject_obj.present() ) {
            this._showMsg($( this._invite_show_div ), 1, "请输入邀请主题");
            this._invite_subject_obj.focus();
            return false;             
        }
        if ( !this._invite_message_obj.present() ) {
            this._showMsg($( this._invite_show_div ), 1, "请输入邀请信息");
            this._invite_message_obj.focus();
            return false;
        }
        return true;
    },
      
    _clearUp : function () {
        this._invite_subject_obj.setValue('');
        this._invite_message_obj.setValue('');
    },
     
    _onCreate : function () {
        this._send_invite_button_obj.disable();
        this._discard_invite_button_obj.disable();
        this._showMsg($( this._invite_show_div ), 2, "邀请发送中, 请稍候。。。");
    },
     
    _onComplete : function () {
        this._send_invite_button_obj.enable();
        this._discard_invite_button_obj.enable();
        this._clearUp();
    },
    
    _fill_invite_message : function () {
        var template = new Template( this._template_invite_message );
        return template.evaluate( this._trans() );
    },
    
    _trans : function () {
        var data = {
            to_name : typeof this._to_user_profile.basicProfile.name == "object" ? "" : this._to_user_profile.basicProfile.name,
            from_name : typeof this._my_profile.basicDetailProfile.name == "object" ? "" : this._my_profile.basicDetailProfile.name,
            my_hz_link : typeof this._my_profile.basicDetailProfile.screenName == "object" ? "" : this._my_profile.basicDetailProfile.screenName
        }
        
        return data;
    }
    
}

var ViewInviteList = {
    
    _ajax_send_url : "/Network.do?action=GET_SEND_INNER_INVITATION",
    
    _ajax_recv_url : "/Network.do?action=GET_RECV_INNER_INVITATION",
    
    _ajax_accept_url : "/Network.do?action=ACCEPT_INNER_INVITATION",
    
    _ajax_ignore_url : "/Network.do?action=IGNORE_INNER_INVITATION",
    
    _ajax_accept_invite_request_url : "/Network.do?action=ACCEPT_INVITATION_REQUEST",
    
    _ajax_ignore_invite_request_url : "/Network.do?action=IGNORE_INVITATION_REQUEST",
    
    _each_page_items : 1000,
    
    _data : null,
    
    _invite_request_data : null,
    
    _invite_list_tbody : "invite_list",
    
    _invite_list_tbody_obj : null,
    
    _msg : "wrong_msg",
    
    _template_view_invite_detail : 'template_view_invite_detail',
    
    _template_view_invite_request_detail : 'template_view_invite_request_detail',
    
    _invite_show_div : 'invite_show_div',
    
    _invite_code : '',
    
    _process_buttons : 'process_buttons',
    
    _process_buttons_obj : null,
    
    _process_buttons_show : false,
    
    _type : 0,
    
    gotoPage : function ( page ) {
        this._resetMsg();
        var needAjax = false;
        if ( location.href.include('inner_invite.jsp#') ) {
            needAjax = true;
        }
        if (page == 0) {
            location.href = 'inner_invite.jsp#send';
        } else if (page == 1) {
            location.href = 'inner_invite.jsp#recv';
        } else if (page == 2) {
            location.href = 'inner_invite.jsp#compose';
        }
        
        if ( needAjax ) {
            InnerInvite.init(INVITE.MY_PROFILE, INVITE.TO_USER_PROFILE);
        }
    },
    
    _initObj : function () {
        this._invite_list_tbody_obj = $( this._invite_show_div ).select('[id='+ this._invite_list_tbody + ']')[0];
        this._process_buttons_obj = $( this._invite_show_div ).select('[id='+ this._process_buttons + ']')[0];
    },
    
    show : function(pageNum, type) {

        this._initObj();
        this._type = type;
        this.lightUl( type );
        var ajaxReq = null;
        if (type == 0) {
            ajaxReq = this._ajax_send_url;
            this._process_buttons_show = false;
        } else {
            ajaxReq = this._ajax_recv_url;
            this._process_buttons_show = true;
        }
        var startIndex = (pageNum - 1) * this._each_page_items;        
        
        var params = new Hash();
        params.set("startIndex", startIndex);
        params.set("maxItemCount", this._each_page_items);
        
        new Ajax.Request(ajaxReq,
        {
            method : "post",
            
            parameters : params.toQueryString(),
            
            requestHeaders : { 
                Accept : "application/json"
            },

            onCreate: function() {
                
            }.bind( this ),
             
            onSuccess : function ( transport ) {
                var json = transport.responseText.evalJSON( true );
                if ( json.RETURN ) {
                    this._data = json.inviteList;
                    if (type == 1) {
                        this._show_inner_invite_count(this._data.size());
                        this._show_invite_mixture_list();
                    } else {
                        this._show_inner_invite_list();
                    }
                } else {
                    this._showMsg($(this._invite_show_div), 1, json.MESSAGE);
                }
            }.bind(this),
            
            onComplete : function () {
                this._onComplete();
            }.bind( this )
            
        });
        
    },
    
    accept : function ( flag ) {
        
        var params = new Hash();
        var ajaxReq = null;
        switch (flag) {
            case 0 : 
                ajaxReq = this._ajax_accept_url;
                params.set("invitecode", this._invite_code);
                break;
            case 1 : 
                ajaxReq = this._ajax_accept_invite_request_url;
                params.set("linkcode", this._invite_code);
                break;
        }
        
        new Ajax.Request(ajaxReq,
        {
            method : "post",
            
            parameters : params.toQueryString(),
            
            requestHeaders : { 
                Accept : "application/json"
            },
            
            onCreate: function(){
                this._onCreate();
            }.bind( this ),
             
            onSuccess : function ( transport ) {
                var json = transport.responseText.evalJSON( true );
                if ( json.RETURN ) {
                    this._showMsg($(this._invite_show_div), 0, '您已经接受了名片');
                } else {
                    this._showMsg($(this._invite_show_div), 1, json.MESSAGE);
                }
            }.bind(this),
            
            onComplete : function () {
                this._onComplete();
            }.bind( this )
                        
        });
        
    },
    
    ignore : function ( flag ) {
 
        var params = new Hash();
        var ajaxReq = null;
        switch (flag) {
            case 0 : 
                ajaxReq = this._ajax_ignore_url;
                params.set("invitecode", this._invite_code);
                break;
            case 1 : 

                ajaxReq = this._ajax_ignore_invite_request_url;
                params.set("linkcode", this._invite_code);
                break;
        }
        
        new Ajax.Request(ajaxReq,
        {
            method : "post",
            
            parameters : params.toQueryString(),
            
            requestHeaders : { 
                Accept : "application/json"
            },
            
            onCreate: function(){
                this._onCreate();
            }.bind( this ),
             
            onSuccess : function ( transport ) {
                var json = transport.responseText.evalJSON( true );
                if ( json.RETURN ) {
                    this._showMsg($(this._invite_show_div), 0, "您已经忽略了对方的名片");
                } else {
                    this._showMsg($(this._invite_show_div), 1, json.MESSAGE);

                }
            }.bind(this),
            
            onComplete : function () {
                this._onComplete();
            }.bind( this )
                        
        });

    },
    
    lightUl : function ( page ) {
        switch ( page ) {
            case 0 : 
                page = '已发出邀请';
                break;
            case 1 :
                page = '收到邀请';
                break;
            case 2 : 
                page = '书写邀请';
                break;
            default :
                page = '书写邀请';
                break;
        }
        var aSelectedPage = $('mailMenu').select('li');
        for(var i=0;i<aSelectedPage.size();i++){
            var tmp = aSelectedPage[i];
            
            if(tmp.innerHTML.include( page )){
                // SET ID=CURRENT, WILL HIGH LIGHT MENU
                tmp.setAttribute('id', 'selected_1');
            }else{
                // REMOVE ALL OTHER ID, IF PRE-SET
                tmp.removeAttribute('id');
            }
        }
        
        
    },
    
    _showMsg : function (obj, type, msg) {
        var msgElement = null;
        if ($('msg') == undefined) {
            msgElement = new Element('div', {
                'id' : 'msg'
            });
        } else {
            msgElement = $('msg');
        }
        switch (type) {
            case 0 :
                msgElement.className = 'ok_message';
                break;
            case 1 :
                msgElement.className = 'wrong_message';
                break;
            case 2 :
                msgElement.className = 'sent_message';
                break;
        }        
        msgElement.update(msg);
        obj.insert( {
            before:msgElement
        } );
    },
        
    _resetMsg : function () {
        if ($('msg') != undefined) {
            $('msg').remove();
        }
    },
    
    _onCreate : function () {
        this._showMsg($(this._invite_show_div), 2, "处理中, 请稍候...");
    },
     
    _onComplete : function () {
        
    },
    
    _show_inner_invite_list : function () {
        this._invite_list_tbody_obj.update();
        for (var i = 0; i < this._data.length; i++) {
            this._invite_list_tbody_obj.insert( this._fill_inner_invite_item( this._trans( this._data[i] ) ) );
        }
    },
    
    // TYPE 0 -- > SHOW INNER INVITE, 1 -- > SHOW INVITE REQUEST
    _show_invite_mixture_list : function () {
        this._invite_list_tbody_obj.update();
        for (var i = 0; i < this._data.length; i++) {
            if (this._data[i].TYPE == 0) {
                this._invite_list_tbody_obj.insert( this._fill_inner_invite_item(this._trans( this._data[i].VALUE ), 0) );
            } else {
                this._invite_list_tbody_obj.insert( this._fill_invite_request_item( this._trans_invite_request( this._data[i].VALUE ) ) );
            }
        }
    },
    
    _show_invitation_request_list : function () {
        for (var i = 0; i < this._invite_request_data.length; i++) {
            var transData = this._trans_invite_request(this._invite_request_data[i]);
            var fillTr = this._fill_invite_request_item(transData);
            this._invite_list_tbody_obj.insert(fillTr);
        //            this._invite_list_tbody_obj.insert( this._fill_invite_request_item( this._trans_invite_request( this._invite_request_data[i] ) ) );
        }
    },
    
    _fill_invite_request_item : function (data) {
        var tr = new Element('tr', {
            'id' : data.invite_code,
            'style' : 'cursor:pointer'
        });
        var td1 = new Element('td');
        if (this._type == 0) {
            td1.update('<a href="#">' + data.to_user_name + '</a>');
        } else {
            td1.update('<a href="#">' + data.from_user_name + '</a>');
        }
        tr.appendChild( td1 );
        var td2 = new Element('td');
        td2.update('<a href="#">' + data.subject + '</a>');
        tr.appendChild( td2 );
        var td3 = new Element('td', {
            'class' : 'sortcol',
            'nowrap' : 'nowrap'
        });
        td3.update( data.create_time );
        tr.appendChild( td3 );
        tr.observe('click', function () {
            $( this._invite_show_div ).update( this._view_invite_request_detail( tr.readAttribute('id') ) );
            this._invite_code = tr.readAttribute('id');
            if (data.unread) {
                this._setReadState(1);
            }
        }.bind( this ));
        
        // SHOW UNREAD INVITATION
        if (data.unread) {
            td1.innerHTML = '<strong>' + td1.innerHTML + '</strong>';
            td2.innerHTML = '<strong>' + td2.innerHTML + '</strong>';
            td3.innerHTML = '<strong>' + td3.innerHTML + '</strong>';
        }
        return tr;        
    },
    
    _trans_invite_request : function ( invite_request ) {
        var trans = {
            from_user_name : invite_request.basicInfo.fromName,
            from_user_email : invite_request.basicInfo.fromEmail,
            photo : '<img src="' + this._getPhotoPath(invite_request) + '">',
            to_user_name : invite_request.toUser.name,
            to_user_screenName : invite_request.toUser.screenName,
            to_user_email : invite_request.toUser.email,
            create_time : this._date(invite_request.basicInfo.createDate),
            subject : invite_request.basicInfo.subject,
            message : URLReplace( invite_request.basicInfo.message ),
            invite_code : invite_request.basicInfo.linkCode,
            connection_path : invite_request.connectionPath,
            unread : invite_request.basicInfo.unRead
        }
        return trans;        
    },
    
    _show_inner_invite_count : function ( count ) {
        if (count > 0) {
            $('invite_new_count').update('(' + count + ')');
        } else {
            $('invite_new_count').update();
        }
    },
    
    // TYPE 0 -- > SHOW RECV ITEMS, 1 -- > SHOW SEND ITEMS
    _fill_inner_invite_item : function (data, type) {
        var tr = new Element('tr', {
            'id' : data.invite_code,
            'style' : 'cursor:pointer'
        });
        var td1 = new Element('td');
        if (this._type == 0) {
            td1.update('<a href="#">' + data.to_user_name + '</a>');
        } else {
            td1.update('<a href="#">' + data.from_user_name + '</a>');
        }
        tr.appendChild( td1 );
        var td2 = new Element('td');
        td2.update('<a href="#">' + data.subject + '</a>');
        tr.appendChild( td2 );
        var td3 = new Element('td', {
            'class' : 'sortcol',
            'nowrap' : 'nowrap'
        });
        td3.update( data.create_time );
        tr.appendChild( td3 );
        tr.observe('click', function () {
            var invitecode = tr.readAttribute('id');
            $( this._invite_show_div ).update( this._view_invitation_detail(invitecode, type) );
            if (data.connection_path != undefined && type == 0) {
                this._fillConnectionPaths( data.connection_path );
            } else {
                $( this._invite_show_div ).select('[id="connection_path_div"]')[0].hide();
            }
            this._initObj();
            // SEND INVITE DO NOT SHOW PROCESS BUTTONS
            if ( !this._process_buttons_show ) {
                this._process_buttons_obj.hide();
            } else {
                this._process_buttons_obj.show();
            // IF UNREAD, SHOW BOLD FONT
            }
            this._invite_code = tr.readAttribute('id');
            if (this._type == 1 && data.unread) {
                this._setReadState(0);
            }
        }.bind( this ));
        
        // SHOW UNREAD INVITATION
        if (this._type == 1 && data.unread) {
            td1.innerHTML = '<strong>' + td1.innerHTML + '</strong>';
            td2.innerHTML = '<strong>' + td2.innerHTML + '</strong>';
            td3.innerHTML = '<strong>' + td3.innerHTML + '</strong>';
        }
        return tr;
    },
    
    _setReadState : function (flag) {
        var params = new Hash();
        params.set("invitecode", this._invite_code);
        var ajaxReq = null;
        switch (flag) {
            case 0 : 
                ajaxReq = "/Network.do?action=SET_INVITATION_READ"
                params.set("invitecode", this._invite_code);
                break;
            case 1 :
                ajaxReq = "/Network.do?action=SET_INVITATION_REQUEST_READ"
                params.set("linkcode", this._invite_code);                
                break;
        }
        
        new Ajax.Request(ajaxReq,
        {
            method : "post",
            
            parameters : params.toQueryString(),
            
            requestHeaders : { 
                Accept : "application/json"
            },
            
            onCreate: function(){
            //                this._onCreate();
            }.bind( this ),
             
            onSuccess : function ( transport ) {
                var json = transport.responseText.evalJSON( true );
                if ( json.RETURN ) {
                //                    this._showMsg($(this._invite_show_div), 0, "您已经忽略了邀请");
                } else {
                    this._showMsg($(this._invite_show_div), 1, json.MESSAGE);
                }
            }.bind(this),
            
            onComplete : function () {
            //                this._onComplete();
            }.bind( this )
                        
        });
        
    },
    
    _trans : function ( data ) {
        var trans = {
            from_user_name : data.fromUser.name,
            from_user_screenName : data.fromUser.screenName,
            from_user_email : data.fromUser.email,
            photo : '<img src="' + this._getPhotoPath(data) + '">',
            to_user_name : data.toUser.name,
            to_user_screenName : data.toUser.screenName,
            to_user_email : data.toUser.email,
            create_time : this._date(data.basicInfo.createDate),
            subject : data.basicInfo.subject,
            message : URLReplace( data.basicInfo.message ),
            invite_code : data.basicInfo.linkCode,
            connection_path : data.connectionPath,
            unread : data.basicInfo.unRead
        }
        return trans;
    },
    
    _getConnectionPathNodeInfo : function (connectionPathNode, i) {
        if (connectionPathNode == undefined || connectionPathNode.length <= i) {
            return null;
        }
        return connectionPathNode[i];
    },
    
    _fillConnectionPath : function ( connectionPath ) {
        var tr = new Element('tr');
        for (var i = 0; i < 2 * connectionPath.size() - 1; i++) {
            var td = new Element('td', {
                'align' : 'center'
            });
            if (i == 0) {
                td.update('" 我 "');
            } else if (i == 1 || i == (2 * connectionPath.size() - 3) ) {
                td.update('<img src="/images/arrow_4.gif">');
            } else if (i % 2 == 0) {
                td.update( connectionPath[ i/2 ].name );
            } else {
                td.update('<img src="/images/arrow_3.gif">');
            }
            tr.appendChild( td );
        }
        $( this._invite_show_div ).select('[id="connection_path_tr"]')[0].insert( tr );
    },
    
    _fillConnectionPath2 : function ( connectionPath ) {
        var tr = new Element('tr');
        for (var i = 0; i < 2 * connectionPath.size() - 1; i++) {
            var td = new Element('td', {
                'align' : 'center'
            });
            if (i == 0 || i == (2 * connectionPath.size() - 2)) {
                
            } else if (i == 1 || i == (2 * connectionPath.size() - 3) ) {
                
            }else if (i % 2 == 0) {
                td.update( connectionPath[ i/2 ].name );
            } else if (i %2 != 0) {
                td.update('<img src="/images/arrow_3.gif">');
            }
            tr.appendChild( td );
        }
        $( this._invite_show_div ).select('[id="connection_path_tr"]')[0].insert( tr );        
    },
    
    _fillConnectionPaths : function ( connectionPaths ) {
        switch ( connectionPaths.size() ) {
            case 1 : 
                this._fillConnectionPath(connectionPaths[0]);
                break;
            case 2 : 
                this._fillConnectionPath(connectionPaths[0]);
                this._fillConnectionPath2(connectionPaths2[1]);
                break;
            case 3 :
                this._fillConnectionPath2(connectionPaths[0]);
                this._fillConnectionPath(connectionPaths[1]);
                this._fillConnectionPath2(connectionPaths[2]);
                break;
        }
    },
    
    _getPhotoPath : function ( data ) {
        var path = null;
        if (data.photo == undefined || data.photo.length == 0) {
            switch (data.gender) {
                case -1 : 
                    path = '/images/man_s.gif';
                    break;
                case 0 : 
                    path = '/images/women_s.gif';
                    break;
                case 1 :
                    path = '/images/man_s.gif';
                    break;
            }
        } else {
            path = data.photo;
        }
        return path;
    },
        
    _date : function ( dateString ) {
        var date = new Date( dateString );
        var year = date.getFullYear();
        var month = date.getMonth();
        month++;
        var day = date.getDate();
        return month + '月' + day + '日';
    },
    
    _view_invitation_detail : function (inviteCode, type) {
        // GET TEMPLATE HTML
        var templateHtml = $( this._template_view_invite_detail ).innerHTML.templateDecode();
        // CREATE AND FILL TEMPLATE
        var template = new Template( templateHtml );
        var data = this._getDataByInviteCode(inviteCode, type);
        if (data == null) {
            return null;
        }
        return template.evaluate( data );
    },
    
    _view_invite_request_detail : function ( inviteCode ) {
        // GET TEMPLATE HTML
        var templateHtml = $( this._template_view_invite_request_detail ).innerHTML.templateDecode();
        // CREATE AND FILL TEMPLATE
        var template = new Template( templateHtml );
        var data = this._getInviteRequestDataByInviteCode( inviteCode );
        if (data == null) {
            return null;
        }
        return template.evaluate( data );        
    },
    
    _getDataByInviteCode : function (inviteCode, type) {
        for (var i = 0; i < this._data.length; i++) {
            if (this._data[i].TYPE == 1) {
                continue;
            }
            var data = null;
            if (type == 0) {
                data = this._trans( this._data[i].VALUE );
            } else {
                data = this._trans( this._data[i] );
            }
            if (data.invite_code == inviteCode) {
                return data;
            }
        }
        return null;
    },
    
    _getInviteRequestDataByInviteCode : function ( inviteCode ) {
        for (var i = 0; i < this._data.length; i++) {
            var data = this._trans_invite_request(this._data[i].VALUE);
            if (data.invite_code == inviteCode) {
                return data;
            }
        }
        return null;        
    }
}

var SignUp = {
     
    _ajax_url : "/Login.do?action=SIGNUP",
     
    _form_id : "signup_form",
     
    _name_id : "name",
     
    _email_id : "email_address",
     
    _passwd1_id : "passwd1",
     
    _passwd2_id : "passwd2",
     
    _verification_code_id : "imageCode",
     
    _activate_result : "",
     
    _invite_code : "",
     
    _ref_code : "",

    _static_invite_code : "",
     
    _msg : "show_msg",
     
    _old_email : "",
     
    _need_activate : false,
     
    _login_link : "<a href='login.jsp'>这里</a>",
     
    _register_div : "register_div",
     
    _signup_tip_div : "signup_tip_div",
     
    activate : function () {
        if (arguments.length < 4) {
            return;
        }

        this._activate_result = arguments[0];
        this._invite_code = arguments[1];
        this._ref_code = arguments[2];
        this._static_invite_code = arguments[3]
        this._old_email = arguments[4];
         
        if (this._activate_result != "") {
            // SHOW ACTIVATED MESSAGE
            if ( this._activate_result.RETURN ) {
                $('name').setValue( this._activate_result.registration.name );
                $('email_address').setValue( this._activate_result.registration.email );            
                this._showJumpMsg("帐户已激活", 5);
            } else {
                show_error_msg(this._msg, this._activate_result.MESSAGE);
            //OPEN public
            //                $("signup").style.display="";
            //                $( this._register_div ).replace( $( this._signup_tip_div ).innerHTML );
            }
        } else if(this._invite_code == "" && this._static_invite_code == "") {
            $("signup").style.display="";
            $( this._register_div ).replace( $( this._signup_tip_div ).innerHTML );
        }    
    },
     
    register : function () {
        if ( !this._validate() ) {
            return;
        }
         
        // SET IF SHOULD ACTIVATE
        if (this._old_email != $F( this._email_id )) {
            this._need_activate = true;
        }
         
        // GET PARAMETERS OF FORM FIELD
        var params = new Hash();
        params.set("name", $F( this._name_id ));
        params.set("email_address", $F( this._email_id ));
        params.set("passwd1", MD5( $F( this._passwd1_id ) ));
        params.set("passwd2", MD5( $F( this._passwd2_id ) ));
        //params.set("imageCode", $F( this._verification_code_id ));
        params.set("invitecode", this._invite_code);         
        params.set("ref", this._ref_code);
        params.set("staticInviteCode", this._static_invite_code);
         
        new Ajax.Request(this._ajax_url,
        {
            method : "post",
            parameters : params.toQueryString(),
            requestHeaders : {
                Accept : "application/json"
            },
            onCreate: function(){
                this._onCreate();
            }.bind( this ),
             
            onSuccess : function (transport) {
                var json = transport.responseText.evalJSON( true );
                 
                if ( json.RETURN ) {
                    if ( this._need_activate ) {
                        show_success_msg(this._msg, "恒知网已将验证邮件发至您的邮箱,请查收");
                        $("register_button").disable();
                    } else {
                        this._showJumpMsg( 5 );
                    }
                } else {
                    show_error_msg(this._msg, json.MESSAGE);
                }
            }.bind( this ),
         
            onComplete : function () {
                this._onComplete();
            }.bind( this )
        });

    },
     
    _validate : function () {

        if ( !$( this._name_id ).present() ) {
            show_error_msg(this._msg, "请输入姓名");
            $( this._name_id ).focus();
            return false;
        }
        if ( !$( this._email_id ).present() ) {
            show_error_msg(this._msg, "请输入电子邮件地址");
            $( this._email_id ).focus();
            return false;
        }
        if ( !$( this._passwd1_id ).present() ) {
            show_error_msg(this._msg, "请输入密码");
            $( this._passwd1_id ).focus();
            return false;
        }
        if ( $F( this._passwd1_id ).length < 6) {
            show_error_msg(this._msg, "密码长度最少6位");
            $( this._passwd1_id ).focus();
            return false;
        }
        if ( !$( this._passwd2_id ).present() ) {
            show_error_msg(this._msg, "请输入重复密码");
            $( this._passwd2_id ).focus();
            return false;
        }
        if ($F( this._passwd1_id ) != $F( this._passwd2_id)) {
            show_error_msg(this._msg, "两次密码不一致");
            $( this._passwd2_id ).focus();
            return false;
        }
        /*
        if ( !$( this._verification_code_id ).present() ) {
            show_error_msg(this._msg, "请输入验证码");
            $( this._verification_code_id ).focus();
            return false;
        }*/
        return true;
    },
     
    _onCreate : function () {
        show_send_msg(this._msg, "处理中, 请稍候...");
    },
     
    _onComplete : function () {
         
    },
     
    _showMsg : function () {
        var succ_msg = "注册成功， 跳转中，请稍候  ...";
        show_success_msg(this._msg, succ_msg);
    },
     
    _showJumpMsg : function (count) {
        this._showMsg();
        setTimeout(function() { 
            location.href = "login.jsp?email_address=" + $F(this._email_id)
        }.bind( this ), 1000 * count);
    },
    
    //xin jun changed for signup.jsp
    showCardForSignup : function(basicProfile){
        
        //初始化数据
        // $("header_index_text_div").style.display ="none";
        $("signupPage_label").update("和 "+basicProfile.name+" 建立联系 | 注册");

    //让空的字段的div不要显示
    //if(basicProfile.occupation == "")
    //$('occupationIdB').style.display ="none";
    //if(basicProfile.industry == ""){
    // $('industryIdB').style.display ="none";
    // }
    //$("degreeWidthBasicImg").style.display ="none";

    }

}
 
var LostPasswd = {
     
    _ajax_validate_email_url : "/Login.do?action=VALIDATE_RESET_PASSWD_EMAIL",
     
    _ajax_reset_passwd_url : "/Login.do?action=RESET_PASSWD",
     
    _email_id : "email_address",
    
    //_birth_month : "birth_month",
    
    //_birth_day : "birth_day",
    
    _birth_place : "birth_place",
    
    _passwd1_id : "passwd1",
     
    _passwd2_id : "passwd2",
     
    _image_code_id : "imageCode",
     
    _lost_passwd_button : "lost_passwd_button",
     
    _login_link : "<a href='login.jsp'>这里</a>",
     
    _msg : "show_msg",
     
    _link_code : "",
     
    _show_lost_passwd_content_div : "LostPassword",
     
    _template_for_validate_email_div : "template_for_validate_email",
     
    _template_for_reset_passwd_div : "template_for_reset_passwd",
     
    init : function () {
        if (arguments.length < 1) {
            return;
        }
         
        this._link_code = arguments[0];
        if (this._link_code != "") {
            $( this._show_lost_passwd_content_div ).update( $( this._template_for_reset_passwd_div ).innerHTML );
        } else {
            $( this._show_lost_passwd_content_div ).update( $( this._template_for_validate_email_div ).innerHTML );
        }
         
        // CLEAR UP TEMPLATE
        $( this._template_for_reset_passwd_div ).remove();
        $( this._template_for_validate_email_div ).remove();
        
    //        if ($(this._birth_month) != undefined) {
    //            this._birth_event();
    //        }
    },
     
    resetPasswd : function () {
        if ( !this._validate_passwd() ) {
            return;
        }
         
        // GET PARAMETERS OF FORM FIELD
        var params = new Hash();
        params.set("linkcode", this._link_code);
        params.set("passwd1", MD5( $F( this._passwd1_id ) ));
        params.set("passwd2", MD5( $F( this._passwd2_id ) ));
         
        new Ajax.Request(this._ajax_reset_passwd_url,
        {
            method : "post",
            parameters : params.toQueryString(),
            requestHeaders : {
                Accept : "application/json"
            },
            onCreate: function(){
                this._onCreate();
            }.bind( this ),
             
            onSuccess : function (transport) {
                var json = transport.responseText.evalJSON( true );
                 
                if ( json.RETURN ) {
                    this._showJumpMsg(json.userEmail, 5);
                } else {
                    show_error_msg(this._msg, json.MESSAGE);
                }
            }.bind( this ),
             
            onComplete : function () {
                this._onComplete();
            }.bind( this )
        });
    },
     
    validateEmail : function () {
        if ( !this._validate_email() ) {
            return;
        }
        
        // GET PARAMETERS OF FORM FIELD
        var params = new Hash();
        params.set("email_address", $F( this._email_id ));
        //params.set("birth_month", $F( this._birth_month ));
        //params.set("birth_day", $F( this._birth_day ));
        params.set("imageCode", $F( this._image_code_id ));
         
        new Ajax.Request(this._ajax_validate_email_url,
        {
            method : "post",
            parameters : params.toQueryString(),
            requestHeaders : {
                Accept : "application/json"
            },
            onCreate: function(){
                this._onCreate();
            }.bind( this ),
             
            onSuccess : function (transport) {
                var json = transport.responseText.evalJSON( true );
                 
                if ( json.RETURN ) {
                    show_success_msg(this._msg, "密码重置邮件已发出，请查收");
                } else {
                    show_error_msg(this._msg, json.MESSAGE);
                }
            }.bind( this ),
             
            onComplete : function () {
                this._onComplete();
            }.bind( this )
        });         
         
    },
    
    _birth_event : function () {
        $( this._birth_month ).observe('keyup', function () {
            if ($F( this._birth_month) < 0 || $F( this._birth_month ) > 12) {
                $( this._birth_month ).setValue('');
            } else if ($F(this._birth_month) > 0 && $F(this._birth_month).length == 2) {
                $( this._birth_day ).setValue('');
                $( this._birth_day ).focus();
            }
        }.bind( this ));
        $( this._birth_day ).observe('keyup', function () {
            if ($F( this._birth_day) < 0 || $F(this._birth_day) > 31) {
                $( this._birth_day ).setValue('');
            } else if ($F(this._birth_day).length == 2) {
                $( this._image_code_id ).focus();
            }
        }.bind( this ));
    },
    
    _validate_email : function () {
        if ( !$( this._email_id ).present() ) {
            show_error_msg(this._msg, "请输入电子邮件地址");
            $( this._email_id ).focus();
            return false;
        }
        //        if ( !$( this._birth_month ).present() ) {
        //            show_error_msg(this._msg, "请输入生日日期");
        //            $( this._birth_month ).focus();
        //            return false;
        //        }
        //        if ( !$( this._birth_day ).present() ) {
        //            show_error_msg(this._msg, "请输入生日日期");
        //            $( this._birth_day ).focus();
        //            return false;
        //        }
        
        if ( !$( this._image_code_id ).present() ) {
            show_error_msg(this._msg, "请输入验证码");
            $( this._image_code_id ).focus();
            return false;
        }
        return true;
    },
     
    _validate_passwd : function () {
        if ( !$( this._passwd1_id ).present() ) {
            show_error_msg(this._msg, "请输入密码");
            $( this._passwd1_id ).focus();
            return false;
        }
        if ($F( this._passwd1_id ).length < 6) {
            show_error_msg(this._msg, "密码长度最少6位");
            $(this._passwd1_id).focus();
            return false;
        }
        if ( !$( this._passwd2_id ).present() ) {
            show_error_msg(this._msg, "请重输入密码");
            $( this._passwd2_id ).focus();
            return false;
        }
        if ($F( this._passwd1_id ) != $F( this._passwd2_id)) {
            show_error_msg(this._msg, "两次输入密码不一致");
            $( this._passwd2_id ).focus();
            return false;
        }
        return true;
    },
     
    _onCreate : function () {
        show_send_msg(this._msg, "处理中, 请稍候...");
    },
     
    _onComplete : function () {
        
    },
     
    _showMsg : function (userEmail) {
        var succ_msg = "新密码激活成功，请<a href='login.jsp?email_address=" + userEmail + "'>登录</a>";
        show_success_msg(this._msg, succ_msg);
    },
     
    _showJumpMsg : function (userEmail, count) {
        this._showMsg(userEmail);
        setTimeout(function() { 
            location.href = "login.jsp?email_address=" + userEmail
        }.bind( this ), 1000 * count);
    }

}

/******************************************************************************
 * CLASS FOR INVITE PAGGING FUNCTION
 ******************************************************************************/
var InvitePagging = {
    
    _pages_list_div : "page_invite_list",
    
    _data : null,
    
    _content_location : "page_invite_content_list",
    
    _present_page_num : 0,
    
    _begin_page_num : 0,
    
    _end_page_num : 0,
    

    _each_page_items : 10,
    
    _list_size : 10,
    
    _max_page_num : 0,
    
    _show_num : true,

    _show_type : 0,
    
    show : function ( pageNum ) {
        // 0 -- > show external invitation, 1 -- > show inner invitation
        if (arguments.length > 1) {
            this._show_type = arguments[1];
        }
        
        // IF THE PAGE IS FIRST OR LAST, SHOW ALERT
        var showValidate = this._showValidate( pageNum );
        if ( !showValidate ) {
            return;
        }
        
        new Ajax.Request(this._getRequestUrl(this._show_type),
        {
            method : "post",
            
            parameters : this._getRequestParam(pageNum).toQueryString(),
            
            requestHeaders : { 
                Accept : "application/json"
            },

            onCreate: function() {
                
            }.bind( this ),
             
            onSuccess : function ( transport ) {
                var json = transport.responseText.evalJSON( true );
                if ( json.RETURN ) {
                    this._data = json.inviteList;
                    this._list_size = json.inviteList.size();
                    this._max_page_num = Math.ceil(json.totalCount / this._each_page_items);
                    this._showPageList( pageNum );
                }
            }.bind(this),
            
            onComplete : function () {
                
            }.bind( this )
            
        });
    },
    
    /*************************** PRIVATE METHOD BEGIN *************************/
    
    // GET REQUEST URL
    _getRequestUrl : function () {
        var reqUrl;
        switch ( this._show_type ) {
            case 0 :
                reqUrl = "/Network.do?action=GET_SEND_EXT_INVITATION";
                break;

            case 1 :
                reqUrl = "/Network.do?action=GET_SEND_INNER_INVITATION";
                break;

            case 2 : 
                reqUrl = "/Network.do?action=GET_RECV_INNER_INVITATION";
                break;
                
            default :
                reqUrl = "/Network.do?action=GET_SEND_EXT_INVITATION";
                break;                            
        }
          
        return reqUrl;     
    },
    
    // GET REQUEST PARAMETER
    _getRequestParam : function ( pageNum ) {
        var startIndex = (pageNum - 1) * this._each_page_items;
        var params = new Hash();        
        params.set("startIndex", startIndex);
        params.set("maxItemCount", this._each_page_items);
        
        return params;
    },
    
    // SHOW IF PAGE IS FIRST PAGE OR LAST PAGE
    _showValidate : function ( pageNum ) {
        if (pageNum < 1) {
            return false;
        } else if (this._max_page_num > 0 && pageNum > this._max_page_num) {
            return false;
        } 
        return true;
    },
    
    // SHOW PAGE LIST AND CONTENT OF PAGE NUMBER
    _showPageList : function ( pageNum ) {
        // CLEAR UP PAGE LIST
        $( this._pages_list_div ).update();
        //        $( this._content_location ).update();
                
        // IF DATA IS EMPTY, DO NOT SHOW PAGE
        if (this._data == null || this._list_size == 0) {
            return;
        }
        this._present_page_num = pageNum;
        // UPDATA PAGE NUMBER LIST
        this._updatePageNumList();
        // COMPOSE PAGE LIST
        this._composePageList();        
        this._showPage( pageNum );        
    },
            
    // SHOW PAGE CONTENT
    _showPage : function ( pageNum ) {
        var pageToBeShow = $('page' + pageNum);
        pageToBeShow.className = 'curp';
        // WHICH PAGE SHOULD BE SHOW
        if (pageNum <= this._max_page_num) {
            ExtInvite.show_ext_invite_list(this._data);
        } 
    }, 
    
    // CREATE PAGE LIST
    _composePageList : function () {
        // FIRST PAGE NAVIGATION
        var firstPage = this._createFirstPage();
        $( this._pages_list_div ).appendChild( firstPage );
        
        // PRE PAGE NAVIGATION
        var prePage = this._createPrePage();
        $( this._pages_list_div ).appendChild( prePage );
        
        // NAVIGATION BY PAGE NUMBER
        for (var i = this._begin_page_num; i < this._end_page_num + 1; i++) {
            var newPage = this._createPage( i );
            $( this._pages_list_div ).appendChild( newPage );
            if ( !this._show_num ) {
                newPage.hide();
            }
        }
        
        // NEXT PAGE NAVIGATION
        var nextPage = this._createNextPage();
        $( this._pages_list_div ).appendChild( nextPage );
        
        // LAST PAGE NAVIGATION
        var lastPage = this._createLastPage();
        $( this._pages_list_div ).appendChild( lastPage );
        
    },

    // CREATE EACH PAGE
    _createPage : function ( n ) {
        var page = new Element("a", {
            "href" : "#",
            "id" : "page" + n
        });
        page.update( n );
        
        page.observe("click", function () {
            this.show(n, this._show_type);
        }.bind(this));
        
        return page;        
    },
    
    // CREATE FIRST PAGE
    _createFirstPage : function () {
        var firstPage = new Element("a", {
            "href" : "#"
        });
        firstPage.update("首页");
        firstPage.observe("click", function () {
            this.show(1, this._show_type);
        }.bind(this));        
        
        return firstPage;
    },
    
    // CREATE PRE PAGE
    _createPrePage : function () {
        var prePage = new Element("a", {
            "href" : "#"
        });
        prePage.update("上一页");
        prePage.observe("click", function () {
            this.show(this._present_page_num - 1, this._show_type);
        }.bind(this)); 
        
        return prePage;
    },
    
    // CREATE NEXT PAGE
    _createNextPage : function () {
        var nextPage = new Element("a", {
            "href" : "#"
        });
        nextPage.update("下一页");
        nextPage.observe("click", function () {
            this.show(this._present_page_num + 1, this._show_type);
        }.bind(this));        

        return nextPage;
    },
    
    // CREATE LAST PAGE
    _createLastPage : function () {
        var lastPage = new Element("a", {
            "href" : "#"
        });
        lastPage.update("末页");
        lastPage.observe("click", function () {
            this.show(this._max_page_num, this._show_type);
        }.bind(this));        
        
        return lastPage;
    },
    
    // UPDATE PAGE NUMBER LIST BY CONDITIONS
    _updatePageNumList : function () {

        // UPDATE PAGE NUMBER LIST IF PRESENT PAGE NUMBER IS FIRST PAGE OR LAST PAGE
        if (this._present_page_num == 1) {
            this._begin_page_num = 1;            
            if (this._max_page_num > 10) {
                this._end_page_num = 10;
            } else if (this._max_page_num > 0) {
                this._end_page_num = this._max_page_num;
            }
        } else if (this._present_page_num == this._max_page_num) {
            this._end_page_num = this._max_page_num;
            if (this._max_page_num > 10) {
                this._begin_page_num = this._max_page_num - 10 + 1;
            } else {
                this._begin_page_num = 1;
            }
        } else {        
            // THE GAP OF PRESENT PAGE NUMBER AND BEGIN PAGE NUMBER
            var stepLen = this._present_page_num - this._begin_page_num;
            
            // IF PAGE NUMBER GAP LARGER THAN 2 AND END PAGE IS NOT MAX PAGE, MOVE RIGHT THE WHOLE PAGE NUMBER LIST
            if ((stepLen > 2) && (this._end_page_num != this._max_page_num)) {

                if (this._present_page_num + 7 > this._max_page_num) {
                    this._end_page_num = this._max_page_num;
                    this._begin_page_num = this._end_page_num - 9;
                } else {
                    this._end_page_num = this._present_page_num + 7;

                    this._begin_page_num = this._end_page_num - 9;
                }

            // IF PRESENT PAGE'S NUMBER MINUS BEGIN PAGE'S NUMBER LESS THAN 2 AND BEGIN PAGE NUMBER IS NOT 1
            // MOVE LEFT THE PAGE NUMBER LIST
            } else if ((stepLen < 2) && (this._begin_page_num != 1)) {

                if (this._present_page_num - 2 < 1) {
                    this._begin_page_num = 1;
                    this._end_page_num = this._begin_page_num + 9;
                } else {
                    this._begin_page_num = this._present_page_num - 2;
                    this._end_page_num = this._begin_page_num + 9;
                }

            } // END OF "else if ((stepLen < 2) && (this._begin_page_num != 1))"
        }
    }
    
/*********************** PRIVATE METHOD END *******************************/
}

var Octazen = {
    
    _ajax_get_url : '/Network.do?action=GET_CONTACTS_BY_OCTAZEN',
    
    _ajax_invite_url : '/Network.do?action=SEND_OCTAZEN_INVITATION',
    
    _octazen_passport : 'octazen_email_address',
    
    _octazen_passwd : 'octazen_passwd',
    
    _radio_id_base : 'email_type',
    
    _show_octazen_content_div : 'show_octazen_content_div',
    
    _get_contacts_div : 'get_contacts_div',
    
    _template_show_contact_list : 'template_show_contact_list',
    
    _template_contact_item : 'template_contact_item',
    
    _template_get_contacts_div : 'template_get_contacts_div',
    
    _octazen_div : 'octazen_div',
    
    _contact_list_table : 'contact_list_table',
    
    _email_size : 0,
    
    _invite_content : 'invite_content2',
    
    _msg : 'contact_msg',
    
    showGetContacts : function () {
        $('octazen_invite_content_table').hide();
        $( this._show_octazen_content_div ).update( $( this._template_get_contacts_div ).innerHTML );
    },
    
    getContacts : function () {
        
        var type = this._getEmailType();
        if (type < 0) {
            show_error_msg(this._msg, "请选择导入类型！");
            return;
        }
        if ( !this._validate() ) {
            return;
        }

        // GET PARAMETERS OF FORM FIELD
        var params = new Hash();
        params.set("type", type);
        params.set("passport", $( this._octazen_div ).select('[id="' + this._octazen_passport + '"]')[0].getValue());
        params.set("passwd", $( this._octazen_div ).select('[id="' + this._octazen_passwd + '"]')[0].getValue());
        
        new Ajax.Request(this._ajax_get_url,
        {
            method : "post",
            parameters : params.toQueryString(),
            requestHeaders : {
                Accept : "application/json"
            },
            onCreate: function(){
                this._onCreate();
            }.bind( this ),
            
            onSuccess : function (transport) {
                var json = transport.responseText.evalJSON( true );
                
                if ( json.RETURN ) {
                    this.resetMsg();
                    this._email_size = json.contactList.length;
                    $( this._show_octazen_content_div ).update( $( this._template_show_contact_list ).innerHTML );
                    $( this._octazen_div ).select('[id="email_type_img"]')[0].replace(this._getEmailImg(type-0));
                    for (var i = 0; i < json.contactList.length; i++) {
                        $( this._octazen_div ).select('[id="' + this._contact_list_table + '"]')[0].insert(this._fillContactItemTemplate(json.contactList[i], i));
                        if (i % 2 != 0) {
                            $( this._octazen_div ).select('[id="tr' + i + '"]')[0].className = 'grey';
                        }

                        if (json.contactList[i].degree == 1) {
                            $('checkbox' + i).replace('<img src="/images/link.gif" />');
                        }else{
                            $('checkbox' + i).checked=true;
                        }
                    }
                    $('octazen_invite_content_table').show();
                } else {
                    show_error_msg(this._msg, json.MESSAGE);
                }
            }.bind( this ),
            
            onComplete : function () {
            //                this._onComplete();
            }.bind( this )
        });         
        
    },
    
    invite : function () {
        var nameEmailHashArray = this._getNameEmailHashArray();
        if (nameEmailHashArray.size() <= 0) {
            show_error_msg(this._msg, "请选择邀请对象");
            return;
        }
        
        //var params = "nameEmailPairs=" + nameEmailHashArray.toJSON() + "&message=" + $F( this._invite_content );
        new Ajax.Request(this._ajax_invite_url,
        {
            method : "post",
            parameters : {
                "nameEmailPairs" : nameEmailHashArray.toJSON(),
                "message" : $F( this._invite_content )
            },
            requestHeaders : {
                Accept : "application/json"
            },
            onCreate: function(){
                this._onCreate();
            }.bind( this ),
            
            onSuccess : function (transport) {
                var json = transport.responseText.evalJSON( true );
                if ( json.RETURN ) {
                    $(this._octazen_div).innerHTML = '<br/><div style="height:25px;width:512px;margin:0px auto;"><div id="contact_msg"></div></div><div class="MarginTop20 text1" align="center"><a href="/invite_import.jsp">返回</a></div>';
                    show_success_msg(this._msg, "邀请发送成功");
                } else {
                    show_error_msg(this._msg, json.MESSAGE);
                }
            }.bind( this ),
            
            onComplete : function () {
            //                this._onComplete();
            }.bind( this )
        });         
    },
    
    checkAll : function (obj) {
        var flag = obj.checked;
        
        for (var i = 0; i < this._email_size; i++) {
            if ($F('enable_tag' + i) == 1) {
                $('checkbox' + i).checked = flag;
            }
        }
    },
    
    check : function (type) {
        $( this._octazen_div ).select('[id="' + 'email_type' + type + '"]')[0].checked = true;
        this._showArrowType(type);
    },
    
    _getEmailImg : function (type) {
        var emailImage = null;
        switch ( type ) {
            case 0 : 
                emailImage = '<img src="/images/msn_logo.gif" />';
                break;
            case 1 :
                emailImage = '<img src="/images/yahoo_logo.gif" />';
                break;
            case 2 : 
                emailImage = '<img src="/images/gmail_logo.gif" />';
                break;
            case 3 :
                emailImage = '<img src="/images/aol_logo.gif" />';
                break;
            default :
                break;
        }
        return emailImage;
    },
    
    _validate : function() {
        if( !$( this._octazen_div ).select('[id="' + this._octazen_passport + '"]')[0].present() ) {
            show_error_msg(this._msg, '请输入账号');
            $( this._octazen_div ).select('[id="' + this._octazen_passport + '"]')[0].focus();
            return false;
        }
        if ( !checkEmail( $( this._octazen_div ).select('[id="' + this._octazen_passport + '"]')[0].getValue() ) ) {
            show_error_msg(this._msg, '邮箱地址格式不正确');
            $( this._octazen_div ).select('[id="' + this._octazen_passport + '"]')[0].focus();
            return false;            
        }
        if( !$( this._octazen_div ).select('[id="' + this._octazen_passwd + '"]')[0].present() ) {
            show_error_msg(this._msg, '请输入密码');
            $( this._octazen_div ).select('[id="' + this._octazen_passwd + '"]')[0].focus();
            return false;
        }
        return true;
    },
    
    _getNameEmailHashArray : function () {
        var nameEmailHashArray = new Array();
        var size = 0;
        for (var i = 0; i < this._email_size; i++) {
            if ($('checkbox' + i) == undefined) {
                continue;
            }
            if ( $('checkbox' + i).checked ) {
                var nameEmailHash = new Hash();
                nameEmailHash.set('name', $F('name' + i));
                nameEmailHash.set('email', $('email_address' + i).innerHTML);
                nameEmailHashArray[size] = nameEmailHash;
                size++;
            }
        }
        return nameEmailHashArray;
    },
    
    _getEmailType : function () {
        var type = -1;
        for (var i = 0; i < 4; i++) {
            var email_type_id = this._radio_id_base + i;
            if ( $( this._octazen_div ).select('[id="' + email_type_id + '"]')[0].checked ) {
                type = $( this._octazen_div ).select('[id="' + email_type_id + '"]')[0].getValue();
                break;
            }
        }
        return type;
    },
    
    _showArrowType : function (type) {
        for (var i = 0; i < 4; i++) {
            var arrow_type_id = 'arrow_left' + i;
            if (i == type) {
                $( this._octazen_div ).select('[id="' + arrow_type_id + '"]')[0].show();
            } else {
                $( this._octazen_div ).select('[id="' + arrow_type_id + '"]')[0].hide();
            }
        }
    },
    
    _fillContactItemTemplate : function (data, data_index) {
        var isEnable = 1;
        if (data.degree == 1) {
            isEnable = 0;
        }
        // TRANSFORM DATA TYPE
        var contactItemData = {
            name : data.name,
            email_address : data.email,
            index : data_index,
            enabled : isEnable
        };
        // GET TEMPLATE HTML
        var templateHtml = $( this._template_contact_item ).innerHTML.templateDecode();
        // CREATE AND FILL TEMPLATE
        var template = new Template( templateHtml );
        var filledTemplate = template.evaluate( contactItemData );
        
        return filledTemplate;
    },
    
    _onCreate : function () {
        show_send_msg(this._msg, '处理中...');
    },
    
    _onComplete : function () {
        $( this._msg ).className = "";
        $( this._msg ).update();
    },
    
    // ONLY USED BY TAB CHANGE
    resetMsg : function () {
        if ($( this._msg ) != undefined) {
            $( this._msg ).className = "";
            $( this._msg ).update();
        }
    }
    
}

var NaviAction = {
    show : function(panelNum){
        $("navibar").hide();
        $("TabbedPanels1").show();
        TabbedPanels1.showPanel(panelNum);
        Octazen.showGetContacts();
    }
}

//Add by Shen
function changeTempContent(e){
    if(e.value == "business"){
        $("invite_content").innerHTML = "我用恒知网建立并保持我的职业联系，特邀请你加入。";
    }
    if(e.value == "friend"){
        $("invite_content").innerHTML = "我最近在用恒知网，上面的微博和网络幻灯片蛮有意思的， 推荐你加入.";
    }
}

function changeTempContent2(e){
    if(e.value == "business"){
        $("invite_content2").innerHTML = "我用恒知网建立并保持我的职业联系，特邀请你加入。";
    }
    if(e.value == "friend"){
        $("invite_content2").innerHTML = "我最近在用恒知网，上面的微博和网络幻灯片蛮有意思的， 推荐你加入.";
    }
}

var SendExtInvitation = {
    _removeExtInvitation : "/Network3.do?action=REMOVE_EXT_INVITATION",

    remove : function(invitationId){
        new Ajax.Request(this._removeExtInvitation,{
            parameters : {
                "invitationId" : invitationId
            },
            requestHeaders : {
                Accept: 'application/json'
            },
            onCreate : function(){
                $("seiLoading_" + invitationId).className = "";
                $("seiLoading_" + invitationId).update('<img src="/images/032.gif" />');
            },
            onSuccess : function(transport){
                var json = transport.responseText.evalJSON(true);
                if(json.RETURN){
                    $("seiMsg_" + invitationId).update("邀请已删除");
                    $("seiMsg_" + invitationId).className = "ok_message";
                    $("seiDelBtn_" + invitationId).remove();
                }else{
                    showMessage($("seiMsg_" + invitationId), json.MESSAGE, false);
                }
            },
            onComplete : function(){
                $("seiLoading_" + invitationId).update();
                $("seiLoading_" + invitationId).className = "clear";
            }
        })
    },

    clickDel : function(form){
        var checkboxs = form.invitationId;
        var invitationIdArr = new Array();
        var y = 0;
        if(typeof checkboxs.length == "undefined"){
            if(checkboxs.checked){
                y++;
            }
        }else{
            for(var i=0; i<checkboxs.length; i++){
                if(checkboxs[i].checked){
                    invitationIdArr[y] = checkboxs[i].value;
                    y++;
                }
            }
        }
        
        if(y == 0){
            showMessage($("extInviteMsg"), "请选择要删除的邀请信息", false);
            setTimeout(function(){
                $("extInviteMsg").update("");
                $("extInviteMsg").className = "clear";
                $("extInviteMsg").className = "clear";
            },3000);
        }else{
            $("extInviteLoading").update('<img src="/images/loading.gif"> 处理中，请稍候...');
            $("clickBtn").setValue("del");
            form.submit();
        }
    },

    paging : function(n, totalPageNum){
        $("clickBtn").setValue("paging");
        var currentPage = Number($("page").getValue());
        var page = currentPage + n;
        if(page < 1){
            $("page").setValue(1);
        }else if(page > totalPageNum){
            $("page").setValue(totalPageNum);
        }else{
            $("page").setValue(page);
            $("inviteForm").submit();
        }
    }
}

function showMessage(div, msg, type) {
    div.update( msg );
    if(type){
        div.className = "ok_message";
    }else{
        div.className = "wrong_message";
    }
}

var OpenSignUp = {

    _form_id : "signup_form",

    _name_id : "name",

    _email_id : "email_address",

    _passwd1_id : "passwd1",

    _passwd2_id : "passwd2",

    _verification_code_id : "imageCode",

    _activate_result : "",

    _invite_code : "",

    _ref_code : "",

    _static_invite_code : "",

    _msg : "show_msg",

    _old_email : "",

    _need_activate : false,

    _login_link : "<a href='login.jsp'>这里</a>",

    _register_div : "register_div",

    _signup_tip_div : "signup_tip_div",

    
    validate : function () {

        //        if ( !$("applycode").present() ) {
        //            show_error_msg(this._msg, "请输入申请码");
        //            $( "applycode" ).focus();
        //            return false;
        //        }
        if ( !$( this._name_id ).present() ) {
            show_error_msg(this._msg, "请输入姓名");
            $( this._name_id ).focus();
            return false;
        }
        if ( !$( this._email_id ).present() ) {
            show_error_msg(this._msg, "请输入电子邮件地址");
            $( this._email_id ).focus();
            return false;
        }
        if(!checkEmail($F( this._email_id ))){
            show_error_msg(this._msg, "电子邮件地址不正确");
            $( this._email_id ).focus();
            return false;
        }
        if ( !$( this._passwd1_id ).present() ) {
            show_error_msg(this._msg, "请输入密码");
            $( this._passwd1_id ).focus();
            return false;
        }
        if ( $F( this._passwd1_id ).length < 6) {
            show_error_msg(this._msg, "密码长度最少6位");
            $( this._passwd1_id ).focus();
            return false;
        }
        if ( !$( this._passwd2_id ).present() ) {
            show_error_msg(this._msg, "请输入重复密码");
            $( this._passwd2_id ).focus();
            return false;
        }
        if ($F( this._passwd1_id ) != $F( this._passwd2_id)) {
            show_error_msg(this._msg, "两次密码不一致");
            $( this._passwd2_id ).focus();
            return false;
        }
        //         if ( !$( this._verification_code_id ).present() ) {
        //             show_error_msg(this._msg, "请输入验证码");
        //             $( this._verification_code_id ).focus();
        //             return false;
        //         }
        $( this._passwd1_id ).value = MD5($F( this._passwd1_id ));
        $( this._passwd2_id ).value = MD5($F( this._passwd2_id ));
        return true;
    }
}

var OpenSignupAddInfo = {
    
    checkForm : function(){
        if(!$("name").present()){
            this._onFailure("请输入您的姓名");
            $("name").focus();
            return false;
        }
        
        if($("gender").getValue() == -1){
            this._onFailure("请选择性别");
            $("gender").focus();
            return false;
        }
        if(!$("location").present()){
            this._onFailure("请输入所在城市");
            $("location").focus();
            return false;
        }
        if($F("wbeginYear") == "" ||$F("wbeginYear") == "YYYY"){
            this._onFailure("请选择工作起始年份");
            $("wbeginYear").focus();
            return false;
        }
        var xxx = $F("wbeginYear");
        if(isNaN(xxx)||xxx < 1960||xxx > 2010){
            this._onFailure("请输入有效工作起始年份");
            $("wbeginYear").focus();
            return false;
        }
        if(!$("company").present()){
            this._onFailure("请输入公司名称");
            $("company").focus();
            return false;
        }
        if(!$("company_weburl").present() || $F("company_weburl").strip() == "http://" || $F("company_weburl").strip() == "https://"){
            this._onFailure("请输入公司网址");
            $("company_weburl").focus();
            return false;
        }
        if(!$("occupation").present()){
            this._onFailure("请输入职位");
            $("occupation").focus();
            return false;
        }
        if($F("beginYear") == ""||$F("beginYear") == "YYYY"){
            this._onFailure("请选择教育背景起始年份");
            $("beginYear").focus();
            return false;
        }
        xxx = $F("beginYear");
        if(isNaN(xxx)||xxx < 1960||xxx > 2010){
            this._onFailure("请输入有效教育背景起始年份");
            $("beginYear").focus();
            return false;
        }

        if($F("endYear") == ""||$F("endYear") == "YYYY"){
            this._onFailure("请选择教育背景结束年份");
            $("endYear").focus();
            return false;
        }
        xxx = $F("endYear");
        if(isNaN(xxx)||xxx < 1960||xxx > 2010){
            this._onFailure("请输入有效教育背景结束年份");
            $("endYear").focus();
            return false;
        }
        if($F("beginYear") > $F("endYear")){
            this._onFailure("教育背景起始年份大于结束年份");
            return false;
        }
        if(!$("school").present()){
            this._onFailure("请输入学校名称");
            $("school").focus();
            return false;
        }
        if(!$("major").present()){
            this._onFailure("请输入专业");
            $("major").focus();
            return false;
        }

        return true;
    },
    
    _onFailure : function(msg){
        $("wrongMsg").show();
        $("wrongMsg").className = "wrong_message";
        $("wrongMsg").update(msg);
    }
}


var Catagory = {

    checkEditForm : function(){
        if(!$("catagory_name").present()){
            this._onFailure("请输入分类名称");
            $("catagory_name").focus();
            return false;
        }
        var form = $('catagory_edit_form');
        var ids = form.getInputs('checkbox', 'friend_id');
        var hasChecked = false;
        for (var index = 0; index < ids.length; ++index) {   
            var item = ids[index];
            if(item.checked){
                hasChecked = true;
                break;
            }
        }
        if(!hasChecked){
            this._onFailure("请选择联系人");
            return false;
        }

        return true;
    },

    _onFailure : function(msg){
        $("wrongMsg").show();
        $("wrongMsg").className = "wrong_message";
        $("wrongMsg").update(msg);
    },

    toggleDisplay: function(catagory_id){
        var content_div = $('catagory_div_id_'+catagory_id);
        var arrow_img = $('catagory_img_id_'+catagory_id);
      
        if(content_div.visible()){
            content_div.hide();
            arrow_img.src = "/images/arrow.png";
        }else{
            content_div.show();
            arrow_img.src = "/images/arrow_1.png";
        }
    },
    toggleSelectAll: function(){
        var all_checkbox = $('all_friends');
        var form = $('catagory_edit_form');
        var ids = form.getInputs('checkbox', 'friend_id');
        
        for (var index = 0; index < ids.length; ++index) {
            var item = ids[index];
            if(all_checkbox.checked){
                item.checked = true;
            }else{
                item.checked = false;
            }
        }
    }
}

var InviteContactDetail = {
    _checkForm : function(){
        if($F("toName").strip() == ""){
            show_error_msg("wrong_msg", "请输入被邀请人的姓名");
            return false;
        }
        if($F("toEmail").strip() == ""){
            show_error_msg("wrong_msg", "请输入被邀请人的邮箱地址");
            return false;
        }
        if(!checkEmail($F("toEmail").strip())){
            show_error_msg("wrong_msg", "请输入正确的邮箱地址");
            return false;
        }
        return true;
    },

    submit : function(){
        var isNeedCheckForm = true;
        if(arguments.length > 0){
            isNeedCheckForm = arguments[0];
        }
        if(isNeedCheckForm && this._checkForm()){
            $("sendForm").submit();
        }
    },

    _removeConfirm : function(){
        if(confirm("确认删除此名片?")){
            return true;
        }
        return false;
    },

    remove : function(){
        if(this._removeConfirm()){
            $("removeContactForm").submit();
        }
    }
}