/**
 * admin/telNo
 */
var mplus_admin_telNo = function(){
	//상속
	mplus_admin.call(this);
	
	var self = this;
	//변수
	var $crudServiceBaseUrl = contextPath + "/admin/telno";
	/**
	 * 초기화
	 */
	this.init = function(){
		initTelNoList(1);
		setPageList(1);
		if($('#page_1')!=null) $('#page_1').addClass('active');
		addEvent();
	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		$('#btnCreate, #btnCreateEmpty').on('click', function(){
			newTelNo();
		});
		$('#btnRemove').on('click', function(){
			removeTelNo();
		});
		$('#btnSave').on('click', function(){
			saveTelNo();
		});
	};
	var telNoList = [];
	var totalCount = '';
	var saveType = '';
	var pageSize = 15;
	
    /**
     * 그리드 초기화
     */
    var initTelNoList = function(page){
    	var opt = {
				url: $crudServiceBaseUrl + "/getList.json",
				type: "post",
				async: false,
				dataType: "json",
				contentType: "application/json",
				data: self.util.stringifyJson({
					pageSize: pageSize, 
					page: page
				})
			};
    	var success = function(result){
    		telNoList = result.data;
    		totalCount = result.totalCount;
    		$('#table_telNo').empty();
    		for(var i=0; i<telNoList.length; i++){
    			var tr = $('<tr></tr>').clone().attr('seq', i);
    			var tdBuildingDesc = $('<td></td>').clone().text(telNoList[i].buildingDesc==null? '': telNoList[i].buildingDesc);
    			var tdRoomDesc = $('<td></td>').clone().text(telNoList[i].roomDesc==null? '': telNoList[i].roomDesc);
    			var tdTelnoOrder = $('<td></td>').clone().text(telNoList[i].telnoOrder==null? '': telNoList[i].telnoOrder);
    			var tdTelValue = $('<td></td>').clone().text(telNoList[i].telValue==null? '': telNoList[i].telValue);
    			
    			$('#table_telNo').append(tr.append(tdBuildingDesc).append(tdRoomDesc).append(tdTelnoOrder).append(tdTelValue));
    			
    			$('#table_telNo tr').on('click', function(e){
    				getTelNoInfo(e.currentTarget.attributes.seq.value);
    				$('#table_telNo tr').removeClass('active');
    				$(this).addClass('active');
    			});
    		}
    		
    		if($('#table_telNo tr')[0]==undefined){
				$('#telNoDetail').css('display', 'none');
				$('#telNoDetailEmpty').css('display', 'block');
			}else{
				$('#table_telNo tr')[0].click();
			}
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
    };
    
    var pageEvent = function(e) {
    	var type = e.currentTarget.id.split('_')[0];
    	var page = Number(e.currentTarget.id.split('_')[1]);
    	
    	if( type == 'page' ) {
    		initTelNoList(page);
    		$('#ulPagination li[id*="page_"]').removeClass('active');
    	} else if ( type == 'next') {
    		initTelNoList(page);
    		setPageList(page);
    	} else if ( type == 'previous' ) {
    		initTelNoList(page);
    		setPageList(page - 9);
    	}
    	
    	if($('#page_'+page)!=null) $('#page_'+page).addClass('active');
    };
    
    var setPageList = function(start) {
    	$('#ulPagination').empty();
    	
    	var end = start + 9;
    	if( Math.ceil(totalCount/pageSize) < end ) {
    		end = Math.ceil(totalCount/pageSize);
    	}
    	
    	if( start > 10 ) {
    		$('#ulPagination').append('<li id="previous_'+(start - 1)+'"><a href="#"><<</a></li>');
    	}
    	    	
    	for( var i = start; i <= end; i++ ) {
    		$('#ulPagination').append('<li id="page_'+i+'"><a href="#">'+i+'</a></li>');
    	}
    	
    	if( end < Math.ceil(totalCount/pageSize) ) {
    		$('#ulPagination').append('<li id="next_'+(end + 1)+'"><a href="#">>></a></li>');
    	}
    	
    	$('#ulPagination li').unbind();
    	$('#ulPagination li').click(function(e) {pageEvent(e);});
    	
    };

    var getTelNoInfo = function(seq){
    	var telNoInfo = telNoList[seq];
    	
    	$('#txtTelnoSeq').val(seq);
    	$('#txtBuildingDesc').val(telNoInfo.buildingDesc);
    	$('#txtRoomDesc').val(telNoInfo.roomDesc);
    	$('#txtTelnoOrder').val(telNoInfo.telnoOrder);
    	$('#txtTelValue').val(telNoInfo.telValue);
    	changeSaveType('edit');
    	
    	$('#telNoDetail').css('display', 'block');
		$('#telNoDetailEmpty').css('display', 'none');
    };
    
    var changeSaveType = function(type){
    	if(type=='edit'){
    		saveType = 'edit';
    	}else{
    		saveType = 'new';
    	}
    };
    
    var newTelNo = function(){
    	changeSaveType('new');
    	
    	$('#txtTelnoSeq').val('');
    	$('#txtBuildingDesc').val('');
    	$('#txtRoomDesc').val('');
    	$('#txtTelnoOrder').val('');
    	$('#txtTelValue').val('');
    	$('#table_telNo tr').removeClass('active');
    	
    	$('#telNoDetail').css('display', 'block');
		$('#telNoDetailEmpty').css('display', 'none');
		
		$('#txtBuildingDesc').focus();
    };
    
    var removeTelNo = function(){
    	if($('#table_telNo tr.active').length==0){
    		alert('삭제할 데이터를 선택해주세요.'); //삭제할 전화번호를 선택해주세요..?
    		return;
    	};
    	if(confirm('해당 전화번호를 삭제하시겠습니까?')){
    		var opt = {
    				url: $crudServiceBaseUrl + "/remove.json",
    				method: "post",
    				dataType: "json",
    				contentType: "application/json",
    				data: self.util.stringifyJson(telNoList[$('#txtTelnoSeq').val()])
    		};
    		
    		var success = function(result){
    			alert("삭제되었습니다.");
    			if(telNoList.length==1){
    				initTelNoList(Number($('#ulPagination li.active')[0].id.split('_')[1])-1);
    			}else{
    				initTelNoList(Number($('#ulPagination li.active')[0].id.split('_')[1]));
    			};
        	};
        	var error = function(xhr,d,t){
        		console.log(xhr);
    			console.log(t);
        	};
        	self.ajaxAdmin( opt, success, error );
    	};
    };
    
    var saveTelNo = function(){
    	var saveUrl = '';
    	if($('#txtBuildingDesc').val()=='' && $('#txtRoomDesc').val()==''){
    		alert('건물명, 호수 중 하나는 필수값 입니다.');
    		return;
    	};
    	if($('#txtTelValue').val()==''){
    		alert('전화번호를 입력해주세요.');
    		return;
    	};
    	
    	if(saveType=='edit'){
    		saveUrl = $crudServiceBaseUrl + "/update.json";
    		var param = telNoList[$('#txtTelnoSeq').val()];
    		param.telNoSeq = $('#txtTelnoSeq').val();
	    	param.buildingDesc = $('#txtBuildingDesc').val();
	    	param.roomDesc = $('#txtRoomDesc').val();
	    	param.telnoOrder = $('#txtTelnoOrder').val();
	    	param.telValue = $('#txtTelValue').val();
    	}else{
    		/*for(var i=0; i<telNoList.length; i++){
				if(managerList[i].userId == $('#txtUserId').val()){
					alert('동일한 아이디가 존재합니다.');
					$('#txtUserId').focus();
					return false;
				}
			};*/
    		saveUrl = $crudServiceBaseUrl + "/save.json";
			var param = {
					telNoSeq: null,
					buildingDesc: $('#txtBuildingDesc').val(),
					roomDesc: $('#txtRoomDesc').val(),
					telnoOrder: $('#txtTelnoOrder').val(),
					telValue: $('#txtTelValue').val()
			}
    	};
    	
    	var opt = {
				url: saveUrl,
				method: "post",
				dataType: "json",
				contentType: "application/json",
				data: self.util.stringifyJson(param)
		};
		
		var success = function(result){
			alert("저장되었습니다.");
			initTelNoList(Number($('#ulPagination li.active')[0].id.split('_')[1]));
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
    };
};