/**
 * @fileoverview 该文件是 xweibo 个人资料设置。
 */
 //var _userInfo = {"edit_tab":"info","sina_uid":1632353457,"nick":"coldera","gender":"m","province":"44","city":"1","description":"\u5f88\u61d2\uff0c\u5f88\u843d\u4f0d","_uploadPicApi":"http%3A%2F%2Fdemo.xweibo.cn%2Findex.php%3Fm%3Dsetting.upload","_savePicApi":"http%3A%2F%2Fdemo.xweibo.cn%2Findex.php%3Fm%3Dsetting.saveAvatar"};

 (function() {

 var 
    UNDEFINED,
    NULL = null,	
	TRUE = true,	
	FALSE = false
 
var match = location.href.match(/#(.+)$/);

var curTab = match ? RegExp.$1 : _userInfo.edit_tab;
 
 var cache = {
    hasSubmit: FALSE,
    curTab: curTab
 };
 
var 
    $ui = window.xform.$ui,
    msg = window.xform.msg,
    cityChange = window.xform.cityChange,
    checkForm = window.xform.checkForm,
    showError = window.xform.showError;
    
  $(document).ready(function() {
    //查找并缓存相关DOM
    var _$tem = $('#container div.form-title strong');
    $ui.infoTab = $(_$tem[0]);
    $ui.photoTab = $(_$tem[1]);
	$ui.showSettingTab = $(_$tem[2]);
	$ui.accountSettingTab = $(_$tem[3]);
    $ui.infoForm = $('#infomation');
    $ui.photoForm = $('#photo');
	$ui.showSettingForm = $('#showSetting');
	$ui.accountSettingForm = $('#accountSetting');
    
    var _$tem = $('#infomation div.form-row');
    $.extend($ui, {
        nick: $(_$tem[0]),
        location: $(_$tem[1]),
        gender: $(_$tem[2]),
        description: $(_$tem[3])
    });
    
    //绑定相关事件
    $ui.infoTab.bind('click', {'type': 'info'}, tabChange);
    $ui.photoTab.bind('click', {'type': 'photo'}, tabChange);
    $ui.showSettingTab.bind('click', {'type': 'show'}, tabChange);
	$ui.accountSettingTab.bind('click', {'type': 'account'}, tabChange);
    
	$('#infoBtn').bind('click', {'type': 'info'}, formSubmit);
	$('#showSettingBtn').bind('click', {'type': 'show'}, formSubmit);
	
    $('#nick')
        .bind('focus', {'type': 'nick'}, showTips)
        .bind('blur', {'type': 'nick'}, checkForm);

    $('#description')
        .bind('blur', {'type': 'description'}, checkForm);
    
    $('#province')
        .bind('change', function(e) {
            cityChange.curProvince = this.value;
            cityChange.createOpt('city');
            
            checkForm('province');
        });
    
    $(document)
        .bind('keyup', function(e) {
            if(e.keyCode == 13) {
                formSubmit(cache.curTab);
            }
        });
    
    cityChange.init();

    setFormValue();
    
    //根据url判断，确定显示哪个tab
	location.href.match(/&tab=(.+)(?:&|$)/);
    var tabName = RegExp.$1;
   
    switch(tabName) {
        case 'displaySet':
            tabChange('show');
            break;
    }
 });
 
 /**
 * 表单输入默认输出
 _userInfo = {"edit_tab":"info","sina_uid":1632353457,"nick":"coldera","gender":"m","province":"44","city":"1","description":"\u5f88\u61d2\uff0c\u5f88\u843d\u4f0d","_uploadPicApi":"http%3A%2F%2Fdemo.xweibo.cn%2Findex.php%3Fm%3Dsetting.upload","_savePicApi":"http%3A%2F%2Fdemo.xweibo.cn%2Findex.php%3Fm%3Dsetting.saveAvatar"};
 */ 
 function setFormValue() {
    if(!_userInfo) {return;}
    
    tabChange(cache.curTab);
    
    if(_userInfo.gender == 'm') {
        $('#male').attr('checked', TRUE);
    }else {
        $('#female').attr('checked', TRUE);
    }
    
    if(_userInfo.province) {
        var $opt = $('#province').find('option[value = '+_userInfo.province+']');
    
        if($opt[0]) {
            try{
                $opt.attr('selected', TRUE);
            }catch(err) {}
            cityChange.curProvince = _userInfo.province;
        }
        
        cityChange.createOpt('city');
        
        $opt = $('#city').find('option[value = '+_userInfo.city+']');
        
        if($opt[0]) {
            setTimeout(function() {$opt.attr('selected', TRUE);},0);
        }
    }
 }
 

 function submitCallback(type, error, info) {
    var $el, msgNum;
 
    if(type == 'info'){
        
        switch(error) {
            case 30001:
                if(info.indexOf('需要提供注册者电子邮箱') != -1) {
                   showError($ui.email, 'email', 8);
                }
                else if(info.indexOf('需要提供注册者密码') != -1) {
                    showError($ui.password, 'pwd', 16);
                }
                else if(info.indexOf('需要提供注册者昵称') != -1) {
                    showError($ui.nick, 'nick', 2);
                }
                else if(info.indexOf('该邮箱地址已被注册') != -1) {
                    showError($ui.email, 'email', 27);
                }
                else if(info.indexOf('需要提供注册者省份') != -1) {
                    showError($ui.location, 'location', 10);
                }
                else if(info.indexOf('昵称重复或者非法') != -1) {
                    showError($ui.nick, 'nick', 3);
                }                
                else{
                    window.XWB && window.XWB.alert({
                        'title': '修改失败',
                        'msg': info
                    });
                }
                break;
            case 30002:
            case 30003:
            case 30004:
            case 30005:
            case 30006:
                showError($ui.nick, 'nick', 25);
                break;
            case 30010:
                showError($ui.description, 'description', 26);
                break;
            case 30011:
                showError($ui.nick, 'nick', 23);
                break;
            case 40001:
                if(info.indexOf('M01129') != -1) {
                   showError($ui.nick, 'nick', 3);
                }else if(info.indexOf('M01119') != -1) {
                    showError($ui.description, 'description', 12);
                }
                break;
            case 40004:
                showError($ui.nick, 'nick', 2);
                break;
            case 40005:
                showError($ui.gender, 'gender', 11);
                break;
            case 40006:
                showError($ui.location, 'province', 10);
                break;
            case 30014:
            case 40008:
                showError($ui.nick, 'nick', 28);
                break;
            case 30015:
            case 40009:
                showError($ui.description, 'description', 29);
                break;
            case 0:
                window.XWB && window.XWB.alert({
                    'title': '提示',
                    'msg': '修改成功'
                });
                break;
            default:
                window.XWB && window.XWB.alert({
                    'title': '提示',
                    //'msg': '修改失败:' + error+':'+info
                    'msg': '修改失败: 信息修改出现错误'
                });
                break;
        }

    }
	
	if (type == 'show') {
		switch(error) {
			case 60003:
                window.XWB && window.XWB.alert({
                    'title': '提示',
                    //'msg': '修改失败:' + error+':'+info
                    'msg': '个人显示设置失败: 修改配置项失败'
                });
				break;
            case 0:
                window.XWB && window.XWB.alert({
                    'title': '提示',
                    'msg': '个人显示项设置成功'
                });
				break;
            default:
                window.XWB && window.XWB.alert({
                    'title': '提示',
                    //'msg': '修改失败:' + error+':'+info
                    'msg': '个人显示设置失败'
                });
                break;
		}
	}
 }
 
/**
* 提交表单数据
*/
 function formSubmit(e) {
    if(cache.hasSubmit) {
        return;
    }

    if(!xform.canSubmit) {
        window.XWB && window.XWB.alert({
            'title': '提示',
            'msg': '请确认填写的信息正确再提交。'
        });
        return;
    }
    
    var type = '';
    if(typeof e == 'object') {
        type = e.data.type;
    }else {
        type = e;
    }
    
    switch(type) {
        case 'info':
            var args = getFormVal('info');
            
            cache.hasSubmit = TRUE;
            
            $.ajax({
                type: 'POST',
                url: window.XWB && window.XWB.url('setting','saveProfile'),
                dataType: 'json',
                data: args,
                success: function(data){

                    var num = data.errno;
                    submitCallback('info', num, data.err);
                    
                    cache.hasSubmit = FALSE;
                }
            });
            break;
        case 'show':
            var args = getFormVal('show');
            
            cache.hasSubmit = TRUE;
            
            $.ajax({
                type: 'POST',
                url: window.XWB && window.XWB.url('setting','saveShowSetting'),
                dataType: 'json',
                data: args,
                success: function(data){

                    var num = data.errno;
                    submitCallback('show', num, data.err);
                    
                    cache.hasSubmit = FALSE;
                }
            });
            break;
    }
 }
 
/**
* 获取表单数据
*/
 function getFormVal(type) {
    var args = {};
 
    switch(type) {
        case 'info':
            $.extend(args, {
                'nick': $('#nick').val(),
                'province': $('#province').val(),
                'city': $('#city').val(),
                'gender': $('#male').attr('checked')? 'm' : 'f',
                'description': $('#description').val()
            });            
            break;
		case 'show':
			$.extend(args, {
				'newfeed': $("input[name='newfeed']:checked").val(),
				'newmsg': $("input[name='newmsg']:checked").val(),
				'feedtotal': $("input[name='feedtotal']:checked").val(),
				'commenttotal': $("input[name='commenttotal']:checked").val()
			});
			break;
    }
    
    return args;
 }
 
 /**
* tab切换
*/
 function tabChange(e) {
    var type = '';
    if(typeof e == 'object') {
        type = e.data.type;
    }else {
        type = e;
    }
    
    cache.curTab = type;
    
    switch(type) {
        case 'info':
            $ui.infoTab.addClass('active');
            $ui.photoTab.removeClass('active');
			$ui.showSettingTab.removeClass('active');
			$ui.accountSettingTab.removeClass('active');
            $ui.infoForm.show();
            $ui.photoForm.hide();
			$ui.showSettingForm.hide();
			$ui.accountSettingForm.hide();
            break;
        case 'photo':
            $ui.photoTab.addClass('active');
            $ui.infoTab.removeClass('active');
			$ui.showSettingTab.removeClass('active');
			$ui.accountSettingTab.removeClass('active');
            $ui.photoForm.show();
            $ui.infoForm.hide();
			$ui.showSettingForm.hide();
			$ui.accountSettingForm.hide();
            break;
        case 'show':
            $ui.showSettingTab.addClass('active');
            $ui.infoTab.removeClass('active');
			$ui.photoTab.removeClass('active');
			$ui.accountSettingTab.removeClass('active');
			$ui.showSettingForm.show();
			$ui.accountSettingForm.hide();
            $ui.photoForm.hide();
            $ui.infoForm.hide();
            break;
        case 'account':
            $ui.accountSettingTab.addClass('active');
            $ui.infoTab.removeClass('active');
			$ui.photoTab.removeClass('active');
			$ui.showSettingTab.removeClass('active');
			$ui.accountSettingForm.show();
			$ui.showSettingForm.hide();
            $ui.photoForm.hide();
            $ui.infoForm.hide();
            break;
    }
    
    //location.href = location.href.replace(/#.+$/, '') + '#' + type;
 }
 
 /**
* 表单提示
*/
 function showTips(e) {
    var $el, msgNum;
    var type = '';
    if(typeof e == 'object') {
        type = e.data.type;
    }else {
        type = e;
    }
    
    switch(type) {
        case 'nick':
            $el = $ui.nick;
            msgNum = 1;
            break;
    }

    $el.find('em.warn').hide();
    var $tips = $el.find('em.tips');
    
    if($tips[0]) {
        $tips.show();
    }else {
        $('<em></em>')
            .addClass('tips')
            .text(msg[msgNum])
            .appendTo($el);
    }
 }
 
 })();
 
