// 발송화면 주소록 :  탭 속성 변경
function chgTab(name) {
	$('address_body').innerHTML = $('tab_layer_'+(name.substr(0,8)=='external' ? 'external' : name)).innerHTML;
	var child_node = $('address_tab').getElementsByTagName('li');
	if(child_node.length>0) {
		var cn;
		for(var i=0;i<child_node.length;i++) {
			cn = child_node[i].className.split('_');
			
			if(cn[0]==name) {
				child_node[i].className = cn[0] + '_on';
			}
			else {
				child_node[i].className = cn[0] + '_off';
			}
		}
	}

	if(name=='book') {
		loadMTAddress('');
	}
	else if(name.substr(0,8)=='external') {
		loadMTExternal(name.replace('external',''));
	}
}

// 발송화면 주소록 : 그룹 및 구성원 로드
function loadMTAddress(sID) {	
	if(sID != '') {
		if(sID != 'AddressPeople' && $('AddressGroup').value=='') {
			alert('그룹이 선택되지 않았습니다.');
			return;
		}

		
		if($('AddressGroup').value=='' && sID == 'AddressPeople') {
			if($('AddressPeopleString').value =='') {
				alert('검색어가 입력되지 않았습니다.');
				return;
			}
			$('AddressGroup').selectedIndex = 1;
			param = '?group_id=-1';
		}
		else {
			param = '?group_id='+$('AddressGroup').value;
		}
			
		param += '&sort='+$('AddressPeopleSort').value + '&searchField=' + $('AddressPeopleField').value + '&searchKey=' + encodeURI($('AddressPeopleString').value);
		
		$('address_lists').innerHTML = '';
		//$('address_lists').className = 'ajaxloading';
		new Ajax.Updater('address_lists','/views/address/address_lists.php' + param, {
			asynchronous:true, 
			evalScripts:true, 
			requestHeaders:['X-Update', 'address_lists']
			}
		);
	}
	else {
		//$('address_body').className = 'ajaxloading';

		new Ajax.Request( '/views/address/address_lists.php?JSON=Y', {
			asynchronous:true,
			evalScripts:true,
			onComplete:function(t) {
				var json = false;

				if($('AddressGroup').length>1) {
					for(var i=$('AddressGroup').length-1;i>0;i--) {
						$('AddressGroup').options[i] = null;
					}
				}

				$('AddressGroup').options[0].value = '';
				$('AddressGroup').options[0].text = '그룹을 선택해 주세요';

				if($('cboQuickRegGroup')!=null) {
					$('cboQuickRegGroup').options[0] = new Option('그룹 미지정' , '');
					$('cboQuickRegGroup').options[0].selected = 'selected';
				}

				json = eval( "(" + t.responseText + ")" );
		
				if(json.resultCode==true) {
					var rows = false;

					rows = eval( "(" + json.GroupInfoLSTVO + ")" );
					for(i=0;i<rows.length;i++) {
						tmpCount = " ("+rows[i].numberOfMember+")";

						cboCount = $('AddressGroup').options.length;
						if(rows[i].GID==0) {
							$('AddressGroup').options[cboCount] = new Option('전체'+tmpCount , '-1');
							//$('AddressGroup').options[cboCount].selected = 'selected';

							if(json.GroupNotSelected != null) {
								tmpCount = " ("+json.GroupNotSelected+")";
							}
							else {
								tmpCount = "";
							}

							//$('AddressGroup').options[cboCount+1] = new Option('그룹 미지정'+tmpCount , 'N');
						}
						else {
							$('AddressGroup').options[cboCount] = new Option(rows[i].groupName + tmpCount , rows[i].GID);

							if($('cboQuickRegGroup')!=null) {
								$('cboQuickRegGroup').options[cboCount-2] = new Option(rows[i].groupName , rows[i].GID);
							}
						}
					}

					if($('address_lists') != null) {
						if($('address_lists').innerHTML=='') {
							$('address_lists').innerHTML = "<input type='hidden' id='MT_address_condition' value=''>";
						}

						if($('warning_loading') != null) {
							$('warning_loading').style.display = 'none';
						}
						
					}

					//$('AddressGroup').selectedIndex = 1;
					//loadMTAddress('-1');
				}
				else {
					alert(json.resultMessage.replace(/\\n/gi,"\n") );
				}					
				//$('address_body').className = '';
			}
		} );
	}

}


// 발송화면 주소록 : 그룹 및 구성원 로드
function loadMTExternal(gtype) {	

		var procURL = '/views/address/external_lists.php';

		if($('ExternalRectime') != null) {
			procURL += "?rectime="+$('ExternalRectime').value;
		}

		if(gtype != 'S' && gtype != 'O') {
			alert('잘못된 외부 주소록 정보입니다.');
			return;
		}

		$('external_lists').innerHTML = '';
		$('external_lists').className = 'ajaxloading';

		new Ajax.Updater('external_lists',procURL, {
			asynchronous:true, 
			evalScripts:true, 
			requestHeaders:['X-Update', 'address_lists']
			}
		);
}



// 주소록 데이터 수신대상 추가
function addAddress(obj) {
	var last_id = null;
	if(obj.disabled == false && obj.checked == true) {

		arrVal = obj.value.split("\t");
		recName = arrVal[0];
		recMobile = arrVal[1];
		recTime = arrVal[2];

		lstCnt = parseInt($('IB_receiverListCnt').value);
		linode = document.getElementsByClassName('LI_receiverLists');

		for(var j=lstCnt ; j<linode.length ; j++ ) {

			var child_item = linode[j].getElementsByClassName('divinfo');
			last_id = 1;
			if(child_item != null) {
				last_id = child_item[0].id.replace(/recLstInfo/gi,'');
			}

			if($('recLstType'+last_id).value == '' && $('recLstKey'+last_id).value == '' && $('recLstName'+last_id).value == '' && $('recLstNum'+last_id).value == '') {
				//$('recLstType'+k).value = "ADDRESS";
				//$('recLstKey'+k).value = recTime.toUpperCase();
				$('recLstName'+last_id).value = recName;
				$('recLstNum'+last_id).value = recMobile.replace(/-/gi,'');
				recChange($('recLstNum'+last_id),'book');
				break;
			}
		}
	}

	if(last_id != null) {
		if($('recLstNum'+(last_id+1)) != null) {
			$('recLstNum'+(last_id+1)).focus();
		}
	}
}



// 선택된 주소록 데이터 수신대상 추가
function addSelect(obj) {
	var items = document.getElementsByClassName(obj);
	if(items == null) return;
	if(items.length == null) return;

	var last_id = 1;
	for(var i=0 ; i < items.length ; i++) {
		addAddress(items[i]);
	}
	$('chkSelectAll').checked  = false;
}


// 현재 조건 전체 추가 (주소록 조건 : book, SFA : sfa)
function addGroup(tp) {
	if($('MT_address_condition') == null) return;
	if($('MT_address_condition').value == '') return;

	//MT_address_condition :  그룹명.chr(9).그룹ID.chr(9).수신시간.chr(9).검색조건.chr(9).검색어.chr(9).수신대상수;
	var arrCondition = $('MT_address_condition').value.split("\t");
	var recCnt = arrCondition[5];

	if($('IB_receiverFromAddress').value.length - $('IB_receiverFromAddress').value.replace("["+$('MT_address_condition').value+"]").length > 0) {
		alert('현재 조건에 만족하는 모든분이 받는사람목록에 이미 추가되어있습니다.');
		return;
	}

	if(recCnt<1) {
		alert('현재 조건에 추가할 대상이 없습니다');
		return;
	}


	lstCnt = parseInt($('IB_receiverListCnt').value);
	linode = document.getElementsByClassName('LI_receiverLists');

	for(var j=lstCnt ; j<linode.length ; j++ ) {

		var child_item = linode[j].getElementsByClassName('divinfo');
		last_id = 1;
		if(child_item != null) {
			last_id = child_item[0].id.replace(/recLstInfo/gi,'');
		}

		if($('recLstType'+last_id).value == '' && $('recLstKey'+last_id).value == '' && $('recLstName'+last_id).value == '' && $('recLstNum'+last_id).value == '') {
			$('recLstType'+last_id).value = 'CONDITION' ;
			$('recLstKey'+last_id).value = $('MT_address_condition').value;
			$('recLstName'+last_id).value = '조건전체' ;
			$('recLstSpan'+last_id).value = '조건전체' ;
			$('recLstNum'+last_id).value = recCnt + "명";
			$('recLstCnt'+last_id).value = recCnt;

			$('recLstName'+last_id).readOnly  = true;
			$('recLstNum'+last_id).readOnly  = true;

			recChange($('recLstNum'+last_id),'book');

			$('IB_receiverListCnt').value = parseInt($('IB_receiverListCnt').value) + 1;
			$('tmp_receiverCnt').innerHTML = parseInt($('tmp_receiverCnt').innerHTML) + parseInt($('recLstCnt'+last_id).value);
			$('IB_receiverCnt').innerHTML = $('tmp_receiverCnt').innerHTML;

			var items = document.getElementsByClassName("chkAddress");
			if(items != null) {
				if(items.length != null) {
					for(var i=0 ; i < items.length ; i++) {
						items[i].checked = true;
						items[i].disabled = true;
					}
				}
			}

			$('IB_receiverFromAddress').value = $('IB_receiverFromAddress').value + "[" + $('MT_address_condition').value + "]";

			var strCondition = '<div>그룹 : ' + arrCondition[0] + '</div>';
			if(arrCondition[2] != '' && arrCondition[2] != '-1')  strCondition += '<br>수신시간 : ' + arrCondition[2].replace('ALL','무관');
			if(arrCondition[4] != '')  {
				strCondition += '<br>검색조건 : ' + arrCondition[3].replace('name','이름').replace('mobile','번호');
				strCondition += '<br><div>검색어 : ' + arrCondition[4] + '</div>';
			}
			
			$('recLstInfo'+last_id).innerHTML = strCondition;
			$('recLstSpan'+last_id).style.display = '';
			$('recLstName'+last_id).style.display = 'none';

			break;
		}
	}
}

/* 조건 정보 레이어 */
function recLayer(tno,tp) {
	if(tp=='V' && $('recLstInfo'+tno).innerHTML != '' ) {
		$('recLstInfo'+tno).style.display = '';
	}
	else {
		$('recLstInfo'+tno).style.display = 'none';
		
	}
}


/* 전화번호 직접입력 */
function chkMobileInput(obj,evt) {
	var str = obj.value;

	if(evt == 32) {
		event.returnValue = false;
	}
	else if(evt=='') {
		var regexp = /[^0-9-\n]/gi
		str = str.replace(regexp,'');

		while (str.indexOf('\n\n') > -1) {
			str = str.replace('\n\n','\n');
		}

		obj.value = str;
	}
}

var directInput = 1;
/* 직접입력 항목 수신대상 추가 */
function addInput(obj) {

	var str = obj.value;

	var regexp = /[^0-9-\n]/gi
	str = str.replace(regexp,'');

	while (str.indexOf('\n\n') > -1) {
		str = str.replace('\n\n','\n');
	}

	if(str.substr(str.length-1,1)=='\n') {
		str = str.substr(0,str.length-1);
	}


	str = str.replace(/\n/gi,',');

	if(str.replace(/,/gi,'') == '') {
		alert('받는사람이 입력되지 않았습니다.');
		return;
	}

	var cnt = str.length - str.replace(/,/gi,'').length + 1;

	if(cnt>100 || (cnt<100 && confirm('받는사람 목록에 통합방식으로 추가하시겠습니까?\n\n  - 확인 : 통합하여 추가\n  - 취소 : 건 단위로 추가'))) {
	
			//alert('직접입력된 항목을 통합 추가시, 중복 및 전화번호 유효성 검사를 하지 않습니다.\n\n실제 수신대상 수와 차이가 있을 수 있습니다.');

			var currentVal = "[" + directInput + "\t" + str + "\t" + directInput + "]";

			lstCnt = parseInt($('IB_receiverListCnt').value);
			linode = document.getElementsByClassName('LI_receiverLists');

			for(var j=lstCnt ; j<linode.length ; j++ ) {

				var child_item = linode[j].getElementsByClassName('divinfo');
				last_id = 1;
				if(child_item != null) {
					last_id = child_item[0].id.replace(/recLstInfo/gi,'');
				}

				if($('recLstType'+last_id).value == '' && $('recLstKey'+last_id).value == '' && $('recLstName'+last_id).value == '' && $('recLstNum'+last_id).value == '') {
					$('recLstType'+last_id).value = 'INPUT_' + directInput;
					$('recLstKey'+last_id).value = currentVal;
					$('recLstName'+last_id).value = '직접입력' ;
					$('recLstSpan'+last_id).value = '직접입력' ;
					$('recLstNum'+last_id).value = str.split(',').length + "명";
					$('recLstCnt'+last_id).value = str.split(',').length;

					$('recLstName'+last_id).readOnly  = true;
					$('recLstNum'+last_id).readOnly  = true;

					recChange($('recLstNum'+last_id),'book');

					$('IB_receiverListCnt').value = parseInt($('IB_receiverListCnt').value) + 1;
					$('tmp_receiverCnt').innerHTML = parseInt($('tmp_receiverCnt').innerHTML) + parseInt($('recLstCnt'+last_id).value);
					$('IB_receiverCnt').innerHTML = $('tmp_receiverCnt').innerHTML;


					$('IB_receiverFromDirectInput').value = $('IB_receiverFromDirectInput').value + currentVal;
					directInput = directInput + 1;

				
					$('recLstInfo'+last_id).innerHTML = '';
					$('recLstSpan'+last_id).style.display = '';
					$('recLstName'+last_id).style.display = 'none';

					obj.value = '';

					break;
				}
			}
	}
	else {
		str = str.replace(/-/gi,'').replace(/\s/gi,'')

		arrStr = str.split(',');
		var last_id = 1;
		for(var i=0 ; i<arrStr.length ; i++) {

			lstCnt = parseInt($('IB_receiverListCnt').value);
			linode = document.getElementsByClassName('LI_receiverLists');

			for(var j=lstCnt ; j<linode.length ; j++ ) {

				var child_item = linode[j].getElementsByClassName('divinfo');
				last_id = 1;
				if(child_item != null) {
					last_id = child_item[0].id.replace(/recLstInfo/gi,'');
				}

				if($('recLstType'+last_id).value == '' && $('recLstKey'+last_id).value == '' && $('recLstName'+last_id).value == '' && $('recLstNum'+last_id).value == '') {
					$('recLstNum'+last_id).value = arrStr[i];
					recChange($('recLstNum'+last_id),'book');
					break;
				}
			}
		}

		if($('recLstNum'+(last_id+1)) != null) {
			$('recLstNum'+(last_id+1)).focus();
		}
	}
	obj.value = '';


}



// 외부주소록(SFA,온메이트) 처리
function procExternal(tp) {
	
	var procURL = '/views/address/external_lists.php';

	
	if(tp=='DELETE') {
		location.href = procURL + '?type=DELETE';
	}
	else {
		$('external_lists').innerHTML = '<div class="address_error"><p style="margin-top:30px;">주소록을 가져오는 중입니다.</p></div>';
		$('external_lists').className = 'ajaxloading';

		if(tp=='INSERT') {
			procURL += '?type=INSERT';
		}

		if($('ExternalRectime') != null) {
			if(tp=='INSERT') {
				procURL += "&";
			}
			else {
				procURL += "?";
			}
			procURL += "rectime="+$('ExternalRectime').value;
		}

		if($('ExternalSort') != null) {
			if($('ExternalRectime') != null) {
				procURL += "&";
			}
			else {
				procURL += "?";
			}
			procURL += "sort="+$('ExternalSort').value;
		}

		new Ajax.Updater('external_lists',procURL, {
			asynchronous:true, 
			evalScripts:true, 
			requestHeaders:['X-Update', 'address_lists']
			}
		);

	}

}



// 빠른등록
function quickReg(tp) {
	if(tp=='cancel' || tp=='completed') {
		$('cboQuickRegGroup').selectedIndex = 0;
		$('txtQuickRegName').value = '';
		$('txtQuickRegMobile').value = '';
		
		$('layerQuickReg').style.display = 'none';

		if(tp=='completed') {
			//if(confirm('주소록에 정상적으로 등록되었습니다.\n\n우측의 개인 주소록을 새로고침 하시겠습니까?')) {
				chgTab('book');
			//}
		}


		return false;
	}

	if($('txtQuickRegName').value.replace(/\s/g,'')=='') {
		alert('추가할 이름을 입력해주세요.');
		$('txtQuickRegName').focus();
		return false;
	}
	else if (isValidMobile($('txtQuickRegMobile').value)==false ) {
		alert('휴대전화번호 형식이 아닙니다.');
		$('txtQuickRegMobile').focus();
		return false;
	}



}


/* 주소록 리스트 views */
function address_view() {
	if($('MT_Address').style.display == ''){
		$('MT_Address').style.display = 'none';
	}else{
		$('MT_Address').style.display = '';
	}
}


/* 최근 발신 목록 */
function mrulists(did) {

	$('btnDeleteMRU').style.display='none';

	if(did != '') {
		/*
		if(did=='ALL' && !confirm("최근발신목록에서 삭제하시겠습니까?")) {
			return;
		}
		*/

		$('mruList').innerHTML = '';
		$('mruList').className = "ajaxloading";

	}
	else {
		if($('layerMRULists').style.display == '') {
			$('layerMRULists').style.display = 'none';
			return;
		}
	}

	new Ajax.Updater('mruList', '/views/main/mrulist.php?did=' + (did != '' ? did : ''), {
		asynchronous:true, 
		evalScripts:true, 
		requestHeaders:['X-Update', 'mruList']
		}
	);

	openLayerPopup('layerMRULists');
}



// 수신대상에 추가
function addMRUSelect() {
	var items = $('mruList').getElementsByTagName('input');
	if(items == null) return;
	if(items.length == null) return;

	var last_id = 1;
	for(var i=0 ; i < items.length ; i++) {
		if(items[i].disabled == false && items[i].checked == true) {

			arrVal = items[i].value.split("\t");
			if(arrVal.length<2) {
				recName = '';
				recMobile = arrVal[0];
				recTime = '';
			}
			else {
				recName = arrVal[0];
				recMobile = arrVal[1];
				recTime = arrVal[2];
			}
			lstCnt = parseInt($('IB_receiverListCnt').value);
			linode = document.getElementsByClassName('LI_receiverLists');

			for(var j=lstCnt ; j<linode.length ; j++ ) {

				var child_item = linode[j].getElementsByClassName('divinfo');
				last_id = 1;
				if(child_item != null) {
					last_id = child_item[0].id.replace(/recLstInfo/gi,'');
				}

				if($('recLstType'+last_id).value == '' && $('recLstKey'+last_id).value == '' && $('recLstName'+last_id).value == '' && $('recLstNum'+last_id).value == '') {
					$('recLstName'+last_id).value = recName;
					$('recLstNum'+last_id).value = recMobile.replace(/-/gi,'');
					recChange($('recLstNum'+last_id),'book');
					break;
				}
			}

		}
	}

	if($('recLstNum'+(last_id+1)) != null) {
		$('recLstNum'+(last_id+1)).focus();
	}
	$('layerMRULists').style.display = 'none';
	return;

}
