/**
 * admin/pushForm
 */
var mplus_admin_pushForm = function(){
	//상속
	mplus_admin.call(this);
	
	var self = this;
	//변수
	var $btnSave = $('#btnSave'),
		$crudServiceBaseUrl = contextPath + "/admin/pushform";
	
	var pushFormList = [];
	var pushFormInfo = {};
	var pageSize = 15;
	/**
	 * 초기화
	 */
	this.init = function(){
		initPushFormList(1);
		setPageList(1);
		if($('#page_1')!=null) $('#page_1').addClass('active');
		initDropdownList();
		addEvent();
		
		$('#sltFormType').on('change', function(e){
			formTypeChange(e.currentTarget.value);
		})
	};
	
	var initDropdownList = function(){
		var opt = {
    			url: contextPath + "/admin/menu/getList.json",
        		type : "POST",
        		dataType : "json"
   	    };
   	    var success = function(data){
			for( var i = 0; i < data.length; i++ ){    
				 var item = data[i];
				 if( (item.accessUriAddr).indexOf(".page") > 0 ){
					 $('#sltMenu').append("<option value='"+ item.menuId+"'>"+item.menuName+"</option>");		
				 }
			};
   	    };
   	    var error = function(xhr,d,t){
   	    	
   	    };
   	    self.ajaxAdmin( opt, success, error );
	}
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		$('#btnCreate, #btnCreateEmpty').on('click', function(){
			newPushForm();
		});
		$btnSave.on('click', function(){
			savePushForm();
		});
	};
	
	var formTypeChange = function(value){
		if(value=='PAGE'){
			$('#formMenu').css('display', 'block');
		}else{
			$('#formMenu').css('display', 'none');
		}
	}
	
	var initPushFormList = 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){
   	    	pushFormList = result.data;
    		totalCount = result.totalCount;
    		$('#table_pushForm').empty();
    		for(var i=0; i<pushFormList.length; i++){
    			var tr = $('<tr></tr>').clone().attr('seq', i).attr('formId', pushFormList[i].formId);
    			var tdFormId = $('<td></td>').clone().text(pushFormList[i].formId);
    			var tdFormType = $('<td></td>').clone().text(pushFormList[i].formType);
    			var tdMenu = $('<td></td>').clone().text(pushFormList[i].menuName==null? '': pushFormList[i].menuName);
    			var tdUseYn = $('<td></td>').clone().text(pushFormList[i].useYn);
    			var tdIncludeNameYn = $('<td></td>').clone().text(pushFormList[i].includeNameYn);
    			var tdFormDesc = $('<td></td>').clone().text(pushFormList[i].formDesc==null? '': self.util.getBytes(pushFormList[i].formDesc)>20? self.util.cut(pushFormList[i].formDesc, 20)+'...': pushFormList[i].formDesc);
    			
    			$('#table_pushForm').append(tr.append(tdFormId).append(tdFormType).append(tdMenu).append(tdUseYn).append(tdIncludeNameYn).append(tdFormDesc));
    			
    			$('#table_pushForm tr').on('click', function(e){
    				getPushFormInfo(e.currentTarget.attributes.seq.value);
    				$('#table_pushForm tr').removeClass('active');
    				$(this).addClass('active');
    			});
    		}
    		if($('#table_pushForm tr')[0]==undefined){
    			$('#pushFormDetail').css('display', 'none');
    			$('#pushFormDetailEmpty').css('display', 'block');
    		}else{
    			$('#table_pushForm tr')[0].click();
    		}
   	    };
   	    var error = function(xhr,d,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' ) {
    		initPushFormList(page);
    		$('#ulPagination li[id*="page_"]').removeClass('active');
    	} else if ( type == 'next') {
    		initPushFormList(page);
    		setPageList(page);
    	} else if ( type == 'previous' ) {
    		initPushFormList(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 getPushFormInfo = function(seq){
    	pushFormInfo = pushFormList[seq];
    	
    	$('#txtFormId').val(pushFormInfo.formId);
    	$('#sltFormType').val(pushFormInfo.formType);
    	formTypeChange(pushFormInfo.formType);
    	$(':radio[name="useYn"][value="'+pushFormInfo.useYn+'"]').prop('checked', true);
    	$('#sltMenu').val(pushFormInfo.menuId);
    	$(':radio[name="includeNameYn"][value="'+pushFormInfo.includeNameYn+'"]').prop('checked', true);
    	$('#txtFormDesc').val(pushFormInfo.formDesc);
    	
    	$('#txtFormId').attr('readonly', true);
    	$('#sltFormType').attr('disabled', true);
    	$('#sltMenu').attr('disabled', true);
    	
    	$('#pushFormDetail').css('display', 'block');
		$('#pushFormDetailEmpty').css('display', 'none');
    };
    
    var newPushForm = function(){
    	pushFormInfo = {};
    	$('#table_pushForm tr').removeClass('active');
    	$('#txtFormId').val('');
    	$('#sltFormType').val('');
    	$(':radio[name="useYn"][value="Y"]').prop('checked', true);
    	$('#sltMenu').val('');
    	$(':radio[name="includeNameYn"][value="Y"]').prop('checked', true);
    	$('#txtFormDesc').val('');
    	$('#txtFormId').attr('readonly', false);
    	$('#sltFormType').attr('disabled', false);
    	$('#sltMenu').attr('disabled', false);
    	
    	$('#pushFormDetail').css('display', 'block');
		$('#pushFormDetailEmpty').css('display', 'none');
		
		$('#txtFormId').focus();
    };
    
    var savePushForm = function(){
    	var param;
    	var opt;
    	if(pushFormInfo.formId==undefined||pushFormInfo.formId==''){
    		var id = $('#txtFormId').val(),
				rex1 = /[~!@\#$%<>^&*\()\-=+\’]/gi,
				rex2 = /\s/gi;
			if( rex1.test(id) ){
				alert("이름은 특수문자를 사용할 수 없습니다.");
				return false;
			} else if( rex2.test(id) ){
				alert("이름은 공백을 포함할 수 없습니다." );
				return false;
			};
    		param = {
    				formId: $('#txtFormId').val(),
    		    	formType: $('#sltFormType').val(),
    		    	useYn: $(':radio[name="useYn"]:checked').val(),
    		    	menuId: $('#sltFormType').val()=='PAGE'? $('#sltMenu').val(): null,
    		    	menuName: $('#sltFormType').val()=='PAGE'? $('#sltMenu option:selected').text(): null,
    		    	includeNameYn: $(':radio[name="includeNameYn"]:checked').val(),
    		    	formDesc: $('#txtFormDesc').val()
    		};
    	}else{
    		param = {
    				formId: pushFormInfo.formId,
    		    	formType: $('#sltFormType').val(),
    		    	useYn: $(':radio[name="useYn"]:checked').val(),
    		    	menuId: $('#sltFormType').val()=='PAGE'? $('#sltMenu').val(): null,
    		    	menuName: $('#sltFormType').val()=='PAGE'? $('#sltMenu option:selected').text(): null,
    		    	includeNameYn: $(':radio[name="includeNameYn"]:checked').val(),
    		    	formDesc: $('#txtFormDesc').val()
    		};
    	};
    	opt = {
				url: $crudServiceBaseUrl + "/save.json",
				method: "post",
				contentType: "application/json",
				data: self.util.stringifyJson(param)
		};
    	
		var success = function(result){
			alert("저장되었습니다.");
			initPushFormList(Number($('#ulPagination li.active')[0].id.split('_')[1]));
			$('#pushFormDetail').css('display', 'none');
			$('#pushFormDetailEmpty').css('display', 'block');
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
    };
};