/**
* For ZLL new Guide system
*
* @Author WuKan
*
* Revision: Guide.js 2010331
*/

var Guide = Guide || {};

Guide.View = {

    init:function(){
    //$.historyInit(Guide.Controller.next);
    },

    /*initPage : function(){
          $('#step_page').find("a[rel='history']").each(function(){
               $(this).click(function(){
                    _self.link_click(this);
                    return false;
               });
          });
     },*/
    /**click link with ajax history way
	*@param domObj
	*/
    /*link_click : function(domObj){
          var hash = domObj.href;
          hash = hash.replace(/^.*#/, '');
          //hash = hash.replace('?', '@');
          $.historyLoad(hash);
     },*/

    /**
     *
     * @param url 'guide/msn'
     * @param param "msnsearch=XXXX&pwd=XXXXXX"
     */
    /*submitForm : function(url,param){
          $.historyLoad(url+'?'+param);
     },*/

    initUploadHead : function(){
	$('#uploadBtn').click(function(){
	    if($('#head_file').val().length>0){
		$('#upload_status').text('上传中...');
		$('#uploadBtn').attr('class','autobtn03');
		$('#uploadBtn').css('pointer','normal');
	    
	    
		/*interval = window.setInterval(function(){
                        var text = $('#upload_status').text();
                        var status = $('#upload_status');
                        if (text.length < 6){
                            status.text(text + '.');                    
                        } else {
                            status.text('上传中');                
                        }
                    }, 200);*/

		$('#UForm').submit();
	    }
	    else
		alert('请选择一个文件。');
	    return false;
	});
	this.bindNextBtn();
    },
    initMyInfo : function(){
	var _self = this;
	//初始化居住地select
	
	SII.dyLoader(SII.Static_url+'js/Profile.js','profile',function(){
		SII.AreaSel("man_livetown", "livein", liveinjson);
		SII.AreaSel("man_hometown", "hometown", hometownjson);
	});
	
	$('#college_name').focus(function(){
	    _self.showProvince();
		if($('#college_name').val() == $('#college_name').attr('defaultVal'))
			$(this).val('').removeClass('quotet');
	});
	$('#college_name').blur(function(){
		var _self = $(this);
		setTimeout(function(){
			if(_self.val().length == 0){
				_defalutVal = _self.attr('defaultVal');
				_self.addClass('quotet').val(_defalutVal);
		}},500);
	});
	this.bindUnivers();
	this.bindNextBtn();
	$('form').keyup(function(e){
		e = e || window.event;
		if(e.keyCode == 13){
			$('#next').click();		
			return false;
		}
	});
	$("form").submit(function() {
		$('#next').click();		
		return false;
	});
	
    },
    /**
       * @mehod Guide.View.changeStepPage : 刷新页面
       *
       * @param htmlpiece{html片段} : 新的局部页面
       * @return 无返回值 
       */
    changeStepPage : function(htmlpiece){
	$('#main').html(htmlpiece);
	window.scrollTo(0,0);
	//jsdebug_log(htmlencode($('#step_page').html()));
    },

    changeStepTitle : function(title){
	document.title = title;
    },
    /**
     * @mehod Guide.View.initMsnSearch : 初始化msn搜索页面
     *
     * @param 无
     * @return 无返回值
     */
    initMsnSearch : function() {
	$('#searchFriend').click(function() {
        var msnemail = $.trim($('#msnemail').val());
	    var bEmail=$(this).attr("substep")=="email";
        var msnpw = $.trim($('#msnpw').val());
        if (bEmail) {
            msnemail += "@" + $("#domain").val();
        }
        if ($.isTrueEmail(msnemail) !== true) {
            SII.Err({
                html:bEmail ? "请填写有效Email地址！" : "请输入有效的msn账号！",
                onHide:function() {
                    $("#msnemail").select();
                }
            });
            return false;
        }
        if (!msnpw) {
            SII.Err({
                html:"请输入正确的密码！",
                onHide:function() {
                    $("#msnpw").select();
                }
            });
            return false;
        }
	    Guide.Controller.msnSearch(msnemail, msnpw, Guide.Controller.settings[bEmail ? "email_url" : "msn_url"]);
	    return false;
	});
	$('#msn_form').submit(function() {
	    $('#searchFriend').click();
	    return false;
	});
	this.bindNextBtn();
	//为邮箱后缀域名的图片绑定事件
	this.bindDomainImg();
    },
    /**
     * 为邮箱后缀域名的图片绑定事件
     */
    bindDomainImg:function() {
	$("[emailDomain]").click(function() {
	    $("#domain").val($(this).attr("emailDomain"));
	    return false;
	});
    },
    /**
     * @mehod Guide.View.fillMsnResult : 刷新好友推荐
     *
     * @param htmlpiece{html} : 新的html片段
     * @return 无返回值
     */
    fillMsnResult : function(htmlpiece) {
	$('#msn_page').html(htmlpiece);
    },
    /**
     * @mehod Guide.View.bindNextBtn : 初始化跳过或者保存按钮
     *
     * @param 无
     * @return 无返回值
     */
	bindNextBtn : function() {
		var _self = this;
		$('.next_btn').click(function() {
			var params = {};
			var _type = $(this).attr('nexttype');
			var _step = $(this).attr('step');
			var _page = $(this).attr('page');
			var _substep = $(this).attr('substep');
			params['type'] = _type;
			params['step'] = _step;
			params["substep"] = _substep;
		    if (_type == 'save' && _page == 'myinfo') {
			var _result = _self.buildProfileData();
			if(!_result){
				return false;
				return;
			}else{
				params['data'] = _self.buildProfileData();
			}
		    }else if (_type == 'save' && _substep) {
			var _return = _self.buildMsnData();
			if (_return == false) {
			    return;
			}
			params['data'] = _return;
			params["url"] = $(this).attr('url');
			//处理好友操作：加为好友、邀请好友
			Guide.Controller.handleFriends(params);
			return;
		    }
		    Guide.Controller.next(params);
		    return false;
		});
    },
    /**
     * @mehod Guide.View.buildMsnData : 构建MSN提交数据
     *
     * @param 无
     * @return "{\"uids\":\""+_uids.join(',')+"\"}"
     */
    buildMsnData : function() {
	var _uids = [];
	$('#select_list').find(':checked').each(function() {
	    _uids.push($(this).val());
	});
	if (_uids.length == 0) {
	    SII.Err('请至少选择一个好友。');
	    return false;
	} else
	    return "{\"uids\":\"" + _uids.join(',') + "\"}";
    },

     /**
       * @mehod Guide.View.initRecommend : 初始化好友推荐页面
       *
       * @param 无
       * @return 无返回值 
       */
     initRecommend : function(){
          this.initchangePerson();//初始化换一换功能
          this.bindNextBtn();
          this.initDelRecommend();//初始化删除单个推荐功能
          this.initGetProfile();//初始化获取用户信息功能
     },

     /**
       * @mehod Guide.View.initRecommendAfterAjax : 在换一换后初始化推荐页面，绑定那些因为换一换而失去的绑定
       *
       * @param 无
       * @return 无返回值 
       */
     initRecommendAfterAjax : function(){
          //ajax刷新后，需要重新绑定获取用户信息及删除单个推荐的功能
          this.initDelRecommend();
          this.initGetProfile();
     },
	   /**
       * @mehod Guide.View.changePerson : 刷新好友推荐
       *
       * @param type{string} : 类型 super/normal
       * @param htmlpiece{html} : 新的html片段
       * @return 无返回值 
       */
     changePerson : function(type,htmlpiece){
          $('#'+type).html(htmlpiece);
          this.initRecommendAfterAjax();
     }
     ,/**
       * @mehod Guide.View.initchangePerson : 初始化换人按钮
       *
       * @param 无
       * @return 无返回值 
       */
	  
     initchangePerson : function(){
          //$('a.change_person').unbind('click');
          $('a.change_person').click(function(){
               var _type =$(this).attr('type'); 
               var url = $(this).attr('url');
               var pagenum = $("#pageInfoInpup").val();

               Guide.Controller.changePerson(url+pagenum);
               return false;
          });
     },

     /**
       * @mehod Guide.View.initGetProfile : 初始化获取用户信息
       *
       * @param 无
       * @return 无返回值 
       */
     initGetProfile : function(){
          //$('a.get_profile').unbind('click');
          $('a.get_profile').click(function(){
               var uid = $(this).attr('uid');
               Guide.Controller.getProfile(uid);
               return false;
          });
     },

     /**
       * @mehod Guide.View.initDelRecommend : 初始化删除单个推荐用户
       *
       * @param 无
       * @return 无返回值 
       */
     initDelRecommend : function(){
	
		   $(".home_friendcommend_close").click(function(){
			 var lis=  $(this).parent().parent().find("li");
			   if(lis.length==1)
			   {
				var bd=$(this).parents(".lg_firbd");
				var title= bd.prev();
				bd.remove();
				title.remove();
			   }
			   else
			   {
			   $(this).parent().remove();
			   }
			   
			   return false;
		   });
         // Friend.Commend.bindCommendEvent($('#normal'),'guide');
		 // Friend.Commend.bindCommendEvent($('#school'),'guide');
		 // Friend.Commend.bindCommendEvent($('#company'),'guide');
		 // Friend.Commend.bindCommendEvent($('#townsman'),'guide');
     },
    /**
     * @mehod Guide.View.initMsnResult : 初始化msn搜索结果页面
     *
     * @param 无
     * @return 无返回值
     */
    initMsnResult : function() {
	$('#all').click(function() {
	    $('#select_list').find(':checkbox').attr('checked', $('#all').attr('checked'));
	});
	$('#select_list').find(':checkbox').click(function() {
	    if ($('#select_list').find(':checkbox').length == $('#select_list').find(':checked').length)
		$('#all').attr('checked', true);
	    else
		$('#all').attr('checked', false);
	});
	this.bindNextBtn();
    },

    /* MY PROFILE by WK*/
    showProvince : function(){
	var _self = this;
	$('#province_part').show();
	$('#province_part').find('a').each(function(){
	    $(this).click(function(){
		_self.getUnivers($(this).attr('uid'));
		return false;
	    });
	});
	$('#univers_part').show();

	var _college = $('#college_name').val();
	var _collegeDefault = $('#college_name').attr('defaultVal');
	if(_college.length > 0 && _college != _collegeDefault){
		//$('#univers_part').find('a[text='+_college+']').click();
	}else{
		this.getUnivers(1);
	}

	$('body').click(function(e){
		e = e || window.event;
		obj = e.srcElement ? e.srcElement : e.target;
		bodyObj = $(this)[0];
		var oldBodyClick = bodyObj.onclick;
		if (obj.tagName != 'INPUT') {
			_self.hideProvince();
		} else {
			if(typeof oldBodyClick == 'function' ){
				//_self.hideProvince();
				oldBodyClick();
			}
		}
	});
    },
    refreshUnivers : function(html){
	$('#univers_part').html(html);
	this.bindUnivers();
    },
	refreshFaculty : function(html){
		$('#faculty_select').html(html);
	},
	bindUnivers : function(){
		var _self = this;
		$('#univers_part').find('a').click(function(){
			_self.getFaculty($(this).attr('uid'));
			$('#college_name').removeClass('quotet').val($(this).text());
			_self.hideProvince();
			$('#faculty_select').focus();
			return false;
		});
	},
	getUnivers : function(provinceId){
		Guide.Controller.getUnivers(provinceId);
	},
	getFaculty : function(UniversId){
		Guide.Controller.getFaculty(UniversId);
	},
	hideProvince : function(){
		$('#province_part').hide();
		$('#univers_part').hide();
	},
	/**
	* @mehod Guide.View.buildProfileData : 构建我的信息提交数据
	*
	* @param 无
	* @return "{\"birthday\":\""+_birthday+"\",\"live_town\":\""+_live_town+"\",\"company_name\":\""+$('#company_name').val()+"\",\"college_name\":\""+$('#college_name').val()+"\"}";
	*/
	buildProfileData : function(){
		
		if(!this.checkMyProfile()){
			SII.Msg('你需要把现居住地、大学、入学年份与家乡都完善好我们才能更好的帮你查找到朋友哦。');
			return false;
		}else{
			var _live_town=_home_town=result='';
			$('#man_livetown select:visible').each(function(){
				if(_live_town.length>0)
					_live_town+='-'+$(this).val();
				else
					_live_town = $(this).val();
			});
			$('#man_hometown select:visible').each(function(){
				if(_home_town.length>0)
					_home_town+='-'+$(this).val();
				else
					_home_town = $(this).val();
			});
			return "{\"live_town\":\""+_live_town+"\",\"company_name\":\""+encodeURIComponent($('#company_name').val())+"\",\"college_name\":\""+$('#college_name').val()+"\",\"faculty\":\""+$('#faculty_select').val()+"\",\"in_year\":\""+$('#in_year').val()+"\",\"home_town\":\""+_home_town+"\"}";
		}
	},
	checkMyProfile : function(){
		if($("select[name='livein[]']").val() ==0 || $('#college_name').val().length == 0 || $('#college_name').val() == $('#college_name').attr('defaultVal') || $("select[name='hometown[]']").val() ==0){
			return false;
		}else
			return true;
	}

	/*initUploadHead : function(){
		$('#uploadBtn').click(function(){
			$('form').submit();
			return false;
		});
		this.bindNextBtn();
	}*/
};

Guide.Controller = {
    settings:{
	changePerson_super_url : '/guide/change_person_super',
	province_url : '/univs/province',
	univers_url : '/univs/univers',
	faculty_url : '/univs/faculty',

	next_url : '/guide/next',
	profile_url : '/profile/view',
	msn_url : '/guide/msn_submit',
	email_url:"/guide/email_submit"
    },


    /**
       * @mehod Guide.Controller.next : 下一步按钮 保存或者跳过都属于下一步
       *
       * @param params{json} : 提交的数据 json格式
       * @return 无返回值 
       */
	next : function(param){
		SII.Ajax(this.settings.next_url,param,function(data){
			if(data.result == 1){
				if(data.msg && data.msg.length > 0){
					SII.Msg(data.msg,function(){
						Guide.View.changeStepPage(data.html.body);
						Guide.View.changeStepTitle(data.html.title);
					});
				}else{
					Guide.View.changeStepPage(data.html.body);
					Guide.View.changeStepTitle(data.html.title);
				}
			}else{
				SII.Err(data.msg);
			}
		},'post');
	},
	/**
       * @mehod Guide.Controller.changePerson : 发送换一换请求
       *
       * @param url{string} : 请求地址
       * @return 无返回值 
       */
     changePerson : function(url){

          SII.Ajax(url,'',function(data){
               if(data.result == 1){
                    if(data.total > data.pagesize)
                         Guide.View.changePerson(data.rtn_type,data.html.body)
                    else if(data.total <= data.pagesize && data.total != 0 ){
                         $(".change_person[type="+data.rtn_type+"]").hide();
                    }
                    else if(data.total == 0){
                         $('#'+data.rtn_type+'_recommend_block').hide();
                    }
               }
               else{
                    SII.Err(data.msg);
               }
          });
     },

     /**
       * @mehod Guide.Controller.getProfile : 获取用户信息请求
       *
       * @param uid{number} : 请求的用户uid
       * @return 无返回值 
       */
     getProfile : function(uid){
          SII.Ajax(this.settings.profile_url,{"uid":uid,"type":"guide"},function(data){
               var oBox = SII.Box({
                    title:data.html.title,
                    content:data.html.body,
                    control:[
                        {
                            color:"$green",
                            text:"加为好友",
                            handle:function() {
                              var nUid = $(this).attr("uid");
                              var nType = 'guide';
                              //location为我可能认识，key接口约定为0
                              var nKey = nType == 2 ? 0 : $(this).attr("key");
                              SII.AddFri({
                                   fuid:uid,
                                   succHandler:function() {
                                        //成功后隐藏添加好友按钮
                                        $('#commend_friend_'+uid).find('a.home_friendcommend_close').click();
                                   }
                              });
                              return false;
                            }
                        },
                        {
                            color:"white",
                            text:"关闭"
                        }
                    ]
                })
          },'get');
     }
	
	,
	
	/*myinfo*/
	/*getProvince : function(){
		var _self = this;
		SII.Ajax(this.settings.province_url,'',function(data){
			Guide.View.showProvince();
		});
		Guide.View.showProvince();
	},*/
    getUnivers : function(p){
	/*SII.Ajax(this.settings.univers_url,'',function(data){
            Guide.View.refreshUnivers();
        });*/
	$.get(this.settings.univers_url,{p:p},function(data){
	    Guide.View.refreshUnivers(data);
	});
    },
    getFaculty : function(u){
	/*SII.Ajax(this.settings.univers_url,'',function(data){
            Guide.View.refreshUnivers();
        });*/
	$.get(this.settings.faculty_url,{u:u},function(data){
	    Guide.View.refreshFaculty(data);
	});
    },

    /**
     * @mehod Guide.Controller.msnSearch : 发送msn搜索请求
     *
     * @param msnemail{string} : msn email
     * @param msnpw{string} : msn 密码
     * @param url {String} 请求地址
     * @return 无返回值
     */
    msnSearch : function(msnemail, msnpw, url) {
        var jqLoadingPassword = $("#loadingPassword").show();
	SII.Ajax(url, {
	    "msnemail":msnemail,
	    "msnpw":msnpw
	}, function(data) {
	    if (data.result == 1) {
		Guide.View.fillMsnResult(data.html.body);
	    }
	    else {
            jqLoadingPassword.hide();
		SII.Err(data.msg);
	    }
    }, 'post', jqLoadingPassword.length);
    },
    /**
     * 处理好友操作：加为好友、邀请好友
     * @param options {Object} 配置参数：
     * {
     *      type:{String} 处理类型，"save"——保存、"skip"——跳过,
     *      step:{String} 当前引导步骤,
     *      data:{Object} json结构字符串，好友信息,
     *      substep:{String} 当前子步骤，"msn"、"email",
     *      url:{String} 请求的url
     * }
     */
    handleFriends:function(options) {
	SII.ajax_compact({
	    url:options.url,
	    data:options,
	    type:"post",
		hideLoading:false,
	    success:function() {
		SII.Confirm({
		    html:"邀请已发送！",
		    title:" ",
		    okText:"继续邀请",
		    cancelText:"下一步",
		    cancelColor:"green",
		    handlecancel:function() {
			Guide.Controller.next($.extend(options, {
			    type:"continue"
			}));
		    }
		});
	    }
	});
    }
};
