function checkGroupForm(){
   if ($('captcha_text') && $F('captcha_text').replace(/[^0-9]/g, '').length != 4) {
      resetCaptcha(); return false;
   }
   return true;
}

function resetCaptcha(not_error) {
   $('captcha_img').src = PUSH_P+'comment/captcha.php?r='+Math.random();
   $('captcha_text').value = '';
   $('captcha_text').focus();
   if (not_error) return;
   Element.show('captcha_msg');
}

function backToGroupPage( gid ){
   redirect(PEOPLE_P+'group/info.php?group_id='+gid);
}

function getGroupForm(){

   var access = 
      Form.getInputs('group_form','radio','input_access_type').find(function(radio) { return radio.checked; }).value;
   var list = $('input_list_type').checked? 0 : 1;

   var args = 'op='+$F('input_op')
            + '&network_id='+$F('input_network_id')
            + '&group_name='+encodeURIComponent($F('input_name'))
            + '&group_description='+encodeURIComponent($F('input_description'))
            + '&grouptype_id='+$F('grouptype_id')
            + '&website='+encodeURIComponent($F('input_website'))
            + '&access_type='+ access
            + '&list_type=' + list;

   if ($('captcha_text')) args += '&user_code='+encodeURIComponent($F('captcha_text').replace(/[^0-9]/g, ''));
   if ($('input_group_id')) args += '&group_id='+$F('input_group_id');
   return args;
}

function submitGroup(){
   if( !checkGroupForm() ) return false;
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: getGroupForm(),
      onSuccess: function(t) {
         hideLoading();
         rsobj = ej(t.responseText);
         if (rsobj.res == 'error') {
            if( rsobj.type == 'error_captcha' )
               resetCaptcha();
            else if( rsobj.type == 'missing' )
               showAlertBox('請輸入必要欄位：群組名稱、描述、類型，以及參與權限等。');
         }else if( rsobj.res == 'ok' ){
            backToGroupPage( rsobj.group_id );
         }
      }
   });
}
function removePicture(gid) {
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      parameters: {'op':'removePicture', 'group_id':gid},
      onSuccess: function(t) {
         hideLoading();
         rsobj = ej(t.responseText);
         if (rsobj.res == 'error') {
            reportError( rsobj.type );
            if( rsobj.type == 'remove_image_fail' ){
               showAlertBox('群組圖片刪除失敗');
            }
         } else if (rsobj.res == 'ok') {
            location.reload();
         }
      }
   });
}
// error handle function
function reportError( type ){
   if( type == 'not_login' ){
      showAlertBox('請重新登入');
   }else if( type == 'group_not_exist' ){
      showAlertBox('此群組不存在');
   }else if( type == 'invalid_group_access_type' ){
      showAlertBox('錯誤的群組存取權限');
   }else if( type == 'member_not_exist' ){
      showAlertBox('找不到與您相關的成員資訊');
   }else if( type == 'not_member' ){
      showAlertBox('您不是此群組的成員');
   }else if( type == 'not_in_group_network' ){
      showAlertBox('您不在此群組所屬的社群網路');
   }else if( type == 'already_member' ){
      showAlertBox('您已經是此群組的成員');
   }else if( type == 'already_apply' ){
      showAlertBox('您已經提出群組加入申請');
   }else if( type == 'be_blocked' ){
      showAlertBox('您無法加入本群組，請與群組管理員聯絡。');
   }else if( type == 'invite_member_exit' ){
      showAlertBox('您邀請的使用者已經是成員或是正在邀請、申請中。');
   }else if( type == 'no_such_user' ){
      showAlertBox('此使用者不存在');
   }else if( type == 'not_friend' ){
      showAlertBox('您只能邀請與您互為好友的使用者喔！');
   }else if( type == 'permission_deny' ){
      showAlertBox('您沒有使用此功能的權限');
   }else if( type == 'invalid_access' ){
      showAlertBox('您沒有執行此功能的群組權限');
   }else{
      showAlertBox('未知的系統錯誤');
   }
}
// generic callback fucntion: check error and return to group page
function groupCallBack( t ){
   hideLoading();
   rsobj = ej(t.responseText);
   if (rsobj.res == 'error') {
      reportError( rsobj.type );
   }else{
      backToGroupPage( rsobj.group_id );
   }
}

// join group
function joinGroup( gid ){
   if(!checkLoginAndReturn("javascript:joinGroup("+gid+");"))
      return;
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: 'op=freeJoin&group_id='+gid,
      onSuccess: groupCallBack
   });
}

function applyJoinGroup( gid ){
   if(!checkLoginAndReturn("javascript:applyJoinGroup("+gid+");"))
      return;
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: 'op=applyJoin&group_id='+gid,
      onSuccess: groupCallBack
   });
}

function cancelApply( gid ){
   if(!checkLoginAndReturn("javascript:cancelApply("+gid+");"))
      return;
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: 'op=cancelApply&group_id='+gid,
      onSuccess: groupCallBack
   });
}

// leave group
function leaveGroup( gid ){
   if(!checkLoginAndReturn("javascript:leaveGroup("+gid+");"))
      return;
   new Dialog()
      .setTitle('離開群組')
      .setBody('您確定要離開這個群組嗎？')
      .setButtons(Dialog.OK_AND_CANCEL)
      .setHandler('doLeaveGroup('+gid+')')
      .setModal(true)
      .show();
}
function doLeaveGroup( gid ){
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: 'op=leave&group_id='+gid,
      onSuccess: groupCallBack
   });
}
// group invitation
function inviteUser(gid){
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: 'op=manageMember&act=invite&group_id='+gid+'&user_id='+encodeURIComponent($F('input_invite')),
      onSuccess: function(t) {
         hideLoading();
         rsobj = ej(t.responseText);
         if (rsobj.res == 'error') {
            reportError( rsobj.type );
         }else if(rsobj.res == 'ok') {
            showAlertBox('邀請成功');
         }
      }
   });
}
// update invitation
function updateInvite( op, gid ){
   if(!checkLoginAndReturn("javascript:updateInvite('"+op+"',"+gid+");"))
      return;
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: 'op='+op+'&group_id='+gid,
      onSuccess: groupCallBack
   });
}
function acceptInvite( gid ){
   updateInvite( 'acceptInvite', gid );
}
function rejectInvite( gid ){
   updateInvite( 'rejectInvite', gid );
}

// invite by Email
function inviteByMail(gid){
   var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

   if( $F('input_invite_email') == '' ){
      alert('no input');
      return false;
   }else if(!$('input_invite_email').value.match(filter)){
      alert('請輸入正確的電子郵件信箱');
   }else{
      showLoading(true);
      new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
         postBody: 'op=sendEmailInvite&group_id='+gid+'&email='+encodeURIComponent($F('input_invite_email')),
         onSuccess: function(t) {
            hideLoading();
            rsobj = ej(t.responseText);
            if (rsobj.res == 'error') {
               alert(rsobj.type);
            }else if(rsobj.res == 'ok') {

            }
         }
      });
   }
}

function updateEmailInvite( op, gid, token ){
   if(!checkLoginAndReturn("javascript:updateEmailInvite('"+op+"',"+gid+",'"+token+"');"))
      return;
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: 'op='+op+'&group_id='+gid+'&token='+token,
      onSuccess: function(t) {
         hideLoading();
         rsobj = ej(t.responseText);
         if (rsobj.res == 'error') {
            alert(rsobj.type);
         }else{
            if( rsobj.type == 'accept' )
               redirect(PEOPLE_P+'group/?group_id='+rsobj.group_id);
            else
               redirect(PEOPLE_P+'group/');
         }
      }
   });
}
function acceptEmailInvite(gid, token){
   updateEmailInvite( 'acceptEmailInvite', gid, token );
}
function rejectEmailInvite(gid, token){
   updateEmailInvite( 'rejectEmailInvite', gid, token );
}

function manageMember(act, gid, uid){
   if(!checkLoginAndReturn("javascript:manageMember('"+act+"',"+gid+",'"+uid+"');"))
      return;

   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: 'op=manageMember&act='+act+'&group_id='+gid+'&user_id='+uid,
      onSuccess: function(t) {
         hideLoading();
         rsobj = ej(t.responseText);
         if (rsobj.res == 'error') {
            reportError( rsobj.type );
         }else if(rsobj.res == 'ok') {
            location.reload();
         }
      }
   });
}

function removeMember( gid, uid ){
   new Dialog()
      .setTitle('移除成員')
      .setBody('您確定要移除這位成員嗎？')
      .setButtons(Dialog.OK_AND_CANCEL)
      .setHandler('manageMember(\'remove\','+gid+','+uid+')')
      .setModal(true)
      .show();
}
function removeAdmin( gid, uid ){
   manageMember('removeAdmin', gid, uid);
}
function addAdmin( gid, uid ){
   manageMember('addAdmin', gid, uid);
}
function acceptMember( gid, uid ){
   manageMember('accept', gid, uid);
}
function rejectMember( gid, uid ){
   manageMember('reject', gid, uid);
}
function blockMember( gid, uid ){
   manageMember('block', gid, uid);
}   
function cancelInvite( gid, uid ){
   manageMember('cancelInvite', gid, uid);
}
function acceptApply( gid, uid ){
   manageMember('accept', gid, uid);
}
function rejectApply( gid, uid ){
   manageMember('reject', gid, uid);
}
// edit member title
function editTitle( mid ){
   Element.hide('member_title_'+mid);
   Element.show('input_title_'+mid);
   Element.show('button_title_'+mid);
   $('input_title_'+mid).focus();
}

function cancelEditTitle( mid ){
   Element.hide('input_title_'+mid);
   Element.hide('button_title_'+mid);
   Element.show('member_title_'+mid);
}

function removeTitle( gid, mid ){
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
      postBody: 'op=removeMemberTitle&group_id='+gid+'&membership_id='+mid,
      onSuccess: function(t) {
         hideLoading();
         rsobj = ej(t.responseText);
         if (rsobj.res == 'error') {
            reportError( rsobj.type );
         }else if(rsobj.res == 'ok') {
            Element.hide('officer_'+rsobj.membership_id);
         }
      }
   });
}

function renameTitle( gid, mid ){
   if( $F('input_title_'+mid) == '' ){
      showAlertBox('請輸入您想要修改的頭銜');
      return false;
   }else{
      showLoading(true);
      new Ajax.Request(PEOPLE_P+'group/group.ajax.php', {
         postBody: 'op=updateMemberTitle&group_id='+gid+'&membership_id='+mid+'&title='+encodeURIComponent($F('input_title_'+mid)),
         onSuccess: function(t) {
            hideLoading();
            rsobj = ej(t.responseText);
            if (rsobj.res == 'error') {
               reportError( rsobj.type );
            }else if(rsobj.res == 'ok') {
               location.reload();
            }
         }
      });
   }
}

function addTitle( gid, mid ){
   new Dialog()
      .setTitle('加入官方成員')
      .setBody(staticField('請輸入官方成員稱謂','<input type="text" id="input_title_'+mid+'" name="input_title_'+mid+'">'))
      .setButtons(Dialog.OK_AND_CANCEL)
      .setHandler('renameTitle('+gid+', '+mid+')')
      .setModal(true)
      .show();
}

function showMailToMemberBox( gid ) {
   var async = new AsyncRequest();
   async.setData({'op':'showMailToMemberBox', 'group_id':gid});
   async.setURI(PEOPLE_P+'group/group.ajax.php');
   new Dialog().setAsync(async).show();
}

function doMailToMember( formname ){
   post_content = Form.serialize(formname);
   post_content += '&msg='+FCKeditorAPI.GetInstance('mailToMember_editor').GetHTML();
   showLoading(true);
   new Ajax.Request(PEOPLE_P+'group/sendmail.ajax.php', {
      postBody: post_content,
      onSuccess: function(t){
         hideLoading();
         rsobj = ej(t.responseText);
         if (rsobj.res == 'error') {
            reportError( rsobj.type );
         }
      }
   });   
}
