if (jQuery) (function($) {
	var _STATUS_SUCCESS = 'SUCCESS';
	var _STATUS_FAIL    = 'FAIL';
	var _STATUS_ERROR   = 'ERROR';
	
	$.ajaxSetup({
		cache: false
	   ,beforeSend:function (xhr, settings) {
		   /*
		   var csrfToken = $('[name=csrfPreventionSalt]:eq(0)').val();
		   if (csrfToken && settings.data) settings.data += '&csrfPreventionSalt=' + csrfToken;
		   */
		}
	});
	
	$.datepicker.setDefaults({
		changeMonth : true,
		changeYear  : true,
		dateFormat  : 'yy.mm.dd'
	});
	
/////////////////////////////////////////////////////////////////////////////////////////

	$.commandAjax = function(commandUrl, formName) {
		var result = {};
		
		$.ajax({
			type    : 'post',
			url     : commandUrl,
			data    : $('#' + formName).serialize(),
			async   : false,
			success : function (response) {
				if (response.status == undefined) {
					result.status  = _STATUS_ERROR;
					result.message = '실행된 JSON 데이터를 받아오지 못했습니다.';
				} else if (response.status == _STATUS_SUCCESS) {
					result.status  = response.status;
					result.message = response.result;
				} else {
					result.status = response.status;
					
					if ($.isArray(response.result)) {
						result.message = '';
						
						$.each(response.result, function (index, collection) {
							result.message += collection.message;
							result.message += '\n';
							//alert(collection.fieldName + ' -> ' + collection.message);
						});
					} else {
						result.message = response.result;
					}
				}
			},
			error : function () {
				result.status  = _STATUS_ERROR;
				result.message = 'HTTP ' + result.status + ' : Network Error !';
			}
		});
		
		return result;
	},
	
	$.commandSubmit = function (options) {
		var opts;
		
		var defaults = {
			commandUrl     : '',
			commandForm    : '',
			commandTarget  : '',
			confirmFlag : true,
			onBeforeSubmit : function () { }
		};

		if (typeof options != 'object') {
			opts = $.extend({}, defaults);
		} else {
			opts = $.extend({}, defaults, options);
		}

		if (opts.onBeforeSubmit != undefined) {
			opts.onBeforeSubmit.call();
		}

		$('#' + opts.commandForm).attr('action', opts.commandUrl).attr('target', opts.commandTarget).submit();
	},
	
	$.commandConfirm = function (options) {
		return $(document.body).each(function () {
			var opts;
			
			var defaults = {
			    commandType    : '',
			    commandUrl     : '',
			    commandForm    : '',
				title          : '확인',
				crtTitle	   : '',				
				message        : '',
				crtMessage	   : '',
				confirmFlag 	: true,
				finishMsgFlag 	: true,
				onBeforeSubmit : function () { 

				},
				onOK           : function () {
					var title = '';
					var onMessageOK;
					var message = '';

					if (options.onBeforeSubmit != undefined) {
						options.onBeforeSubmit.call();
					}
					
					var ajaxMessage = $.commandAjax(options.commandUrl, options.commandForm);
					
					if (ajaxMessage.status == _STATUS_SUCCESS) {
						title = '확인';
						onMessageOK = options.onSuccessOK;
					} else if (ajaxMessage.status == _STATUS_FAIL) {
						title = '오류';
						onMessageOK = options.onFailOK;
					} else {
						title = '오류';
						onMessageOK = options.onFailOK;
					}
					
					message = ajaxMessage.message;
					
					if(!opts.finishMsgFlag) {
						message = '';
					}
						
					$.message({
						title       : title,
						message     : message, //message.replace(/\n/g, '<br />'),
						onMessageOK : onMessageOK
					});
					
				}
			};

			if (typeof options != 'object') {
				opts = $.extend({}, defaults);
			} else {
				opts = $.extend({}, defaults, options);
			}

			if (opts.commandType == 'save') {
				if(opts.crtTitle == '') opts.title   = '저장확인'; 
				else opts.title = opts.crtTitle; 
				if(opts.crtMessage == '') opts.message  = '저장하시겠습니까?'; 
				else opts.message = opts.crtMessage;
		    } else if (opts.commandType == 'insert') {
				if(opts.crtTitle == '') opts.title   = '등록확인'; 
				else opts.title = opts.crtTitle; 
				if(opts.crtMessage == '') opts.message  = '등록하시겠습니까?'; 
				else opts.message = opts.crtMessage;
			} else if (opts.commandType == 'update') {
				if(opts.crtTitle == '') opts.title   = '수정확인'; 
				else opts.title = opts.crtTitle; 
				if(opts.crtMessage == '') opts.message  = '수정하시겠습니까?'; 
				else opts.message = opts.crtMessage;
			} else if (opts.commandType == 'delete') {
				if(opts.crtTitle == '') opts.title   = '저장확인'; 
				else opts.title = opts.crtTitle; 
				if(opts.crtMessage == '') opts.message  = '삭제하시겠습니까?'; 
				else opts.message = opts.crtMessage;
			} else if (opts.commandType == 'saveEng') {
				if(opts.crtTitle == '') opts.title   = 'Confirm'; 
				else opts.title = opts.crtTitle; 
				if(opts.crtMessage == '') opts.message  = 'Do you want to save it?'; 
				else opts.message = opts.crtMessage;
			} else if (opts.commandType == 'apply') {
				if(opts.crtTitle == '') opts.title   = '신청확인'; 
				else opts.title = opts.crtTitle; 
				if(opts.crtMessage == '') opts.message  = '신청하시겠습니까?'; 
				else opts.message = opts.crtMessage;
			} else if (!opts.message) {
				if(opts.crtTitle == '') opts.title   = '실행확인'; 
				else opts.title = opts.crtTitle;
				if(opts.crtMessage == '') opts.message  = '실행하시겠습니까?'; 
				else opts.message = opts.crtMessage;
			}
			
			if(opts.confirmFlag) {
				$.confirm(opts);
			} else {
				$.noConfirm(opts);
			}
		});
	},

	
	$.confirm = function (options) {
		return $(document.body).each(function () {
			var opts;
			var defaults = {
				title   : '확인!',
				message : '명령을 실행하시겠습니까?'
			};
			
			if (typeof options != 'object') {
				opts = $.extend({}, defaults);
			} else {
				opts = $.extend({}, defaults, options);
			}
			
			if (confirm(opts.message)) {
				if (typeof(opts.onOK) != undefined) {
					opts.onOK.call();
				}
			} else {
				if (opts.onCancel != undefined) {
					opts.onCancel.call();
				}
			}
			
			/*
			var divId = 'confirmDialog' + Math.floor(Math.random() * 10000 + 1);
			var confirmDialog = $('<div id="' + divId + '"><span style="display:inline-block;"></span>' + opts.message + '</div>');
			
			$(confirmDialog).dialog({
				autoOpen : true,
				show     : 'fade',
				hide     : 'fade',
				modal    : true,
				height   : 180,
				width    : 400,
				title    : opts.title,
				buttons  : {
					OK : function() {
						$(confirmDialog).dialog('close');
						
						if (typeof(opts.onOK) != undefined) {
							opts.onOK.call();
						}
						
						$(confirmDialog).remove();
					},
					Cancel : function () {
						$(confirmDialog).dialog('close');

						if (opts.onCancel != undefined) {
							opts.onCancel.call();
						}
						
						$(confirmDialog).remove();
					}
				}
			});
			*/

		});
	},
	
	$.noConfirm = function (options) {
		return $(document.body).each(function () {
			var opts;
			var defaults = {
					title   : '',
					message : ''
				};
			if (typeof options != 'object') {
				opts = $.extend({}, defaults);
			} else {
				opts = $.extend({}, defaults, options);
			}
			
			if (typeof(opts.onOK) != undefined) {
				opts.onOK.call();
			}
		});
	},
	
	$.message = function (options) {
		return $(document.body).each(function () {
			var opts;
			var defaults = {
				title   : '확인',
				message : ''
			};
			
			if (typeof options != 'object') {
				opts = $.extend({}, defaults);
			} else {
				opts = $.extend({}, defaults, options);
			}
						
			if(opts.message != '') alert(opts.message);
			
			if (opts.onMessageOK != undefined) {
				opts.onMessageOK.call();
			}
			
			/*
			var divId = 'messageDialog' + Math.floor(Math.random() * 10000 + 1);
			var messageDialog = $('<div id="' + divId + '"><span style="display:inline-block;"></span>' + opts.message + '</div>');
			
			$(messageDialog).dialog({
				autoOpen : true,
				show     : 'fade',
				hide     : 'fade',
				modal    : true,
				height   : 'auto',
				width    : 500,
				title    : opts.title,
				buttons  : {
					OK : function() {
						$(messageDialog).dialog('close');
						
						if (opts.onMessageOK != undefined) {
							opts.onMessageOK.call();
						}
						
						$(messageDialog).remove();
					}
				}
			});
			*/
		});
	},
	
	$.checkboxAll = function (allCheckbodId, childCheckboxName) {
		var childCheckbox = 'input[name$=' + childCheckboxName + ']:checkbox';
		
		$(allCheckbodId).on('click', function () {
			if ($(allCheckbodId).prop('checked')) {
				$(childCheckbox).prop('checked', 'checked');
			} else {
				$(childCheckbox).removeAttr('checked');
			}
		});
		$(childCheckbox).on('click', function() {
			if ($(childCheckbox + ':not(:checked)').length > 0) {
				$(allCheckbodId).removeAttr('checked');
			} else {
				$(allCheckbodId).prop('checked', 'checked');
			}
		});
	};
	
	
	/**
	 * 달력 2개 이용시 날짜 validator 체크
	 * Date Range
	 */
	$.fn.dateRange = function() {
		if ($(this).size() > 1) {
			var from = $(this).eq(0).prop('id');
			var to = $(this).eq(1).prop('id');
			var hap = '#' + from + ', #' + to;
			var dates = $(hap).datepicker({
				onSelect : function(selectedDate) {
					var option = this.id == from ? 'minDate' : 'maxDate',
						instance = $(this).data('datepicker');
						date = $.datepicker.parseDate(
							instance.settings.dateFormat ||
							$.datepicker._defaults.dateFormat,
							selectedDate, instance.settings );
					dates.not(this).datepicker('option', option, date);
				}
			});
		} else if ($(this).size() == 1) {
			$(this).datepicker();
		}	
	};
})(jQuery);


/**
 * SelectBox 변경시 하위depth 추가 AJAX
 *
 * example
 * $(document).on('change', '[id^=boxCode]', function () {
 *    var data = { schafsedcCode : $(this).val() };
 *    fnCommonSelectBoxAddAjax(this, 'SbjectDplmabilityCode.do', data);
 * });
 * 
 * <select id="boxCode1" name="boxCode1"></select>
 * <select id="boxCode2" name="boxCode2"></select>
 * <select id="boxCode3" name="boxCode3"></select>
 * <select id="boxCode4" name="boxCode4"></select>
 * 
 * QUERY FIELD NAME : code, label
 * <option value="'+code+'">'+label+'</option>
 */
function fnCommonSelectBoxAddAjax(obj, url, data) {
	var defaultId = $(obj).prop('id'); // default id name
    var idx = parseInt(defaultId.split('').reverse()[0], 10); // SelectBox index
    defaultId = defaultId.substr(0, defaultId.length -1);
    var nextId = defaultId + (idx + 1);
    
    $('[id^='+defaultId+']').slice(idx).not(obj).remove();
    if (!$(obj).val()) return;
    var _this = obj;
    
    $.ajax({
        url      : url,
        dataType : 'JSON',
        data     : data,
        success  : function (result) {
            if (result.length > 0) {
            	$(_this).after('<select id="'+nextId+'" name="'+nextId+'" />');
                $('#'+nextId).append('<option value="">선택</option>');
                for (var i = 0; i < result.length; i++) {
                    $('#'+nextId).append('<option value="'+result[i].code+'">'+result[i].label+'</option>');
                }
            }
        }
    });
}


function fnCommonIdSelectBoxAddAjax(id, url, data) {
    var idx = parseInt(id.split('').reverse()[0], 10); // SelectBox index
    id = id.substr(0, id.length -1);
    var nextId = id + (idx + 1);
    
    $('[id^='+id+']').slice(idx).not(obj).remove();
    if (!$('#' + id).val()) return;
    
    $.ajax({
        url      : url,
        dataType : 'JSON',
        data     : data,
        success  : function (result) {
            if (result.length > 0) {
                $('#' + id).after('<select id="'+nextId+'" name="'+nextId+'" />');
                $('#'+nextId).append('<option value="">선택</option>');
                for (var i = 0; i < result.length; i++) {
                    $('#'+nextId).append('<option value="'+result[i].code+'">'+result[i].label+'</option>');
                }
            }
        }
    });
}

//중복 제거
//ex ) 배열.removeDup()
Array.prototype.removeDup=function(){
	var resultArray = [];
	if(this==null||this==undefined){		
	} else {
		for(var i=0;i<this.length;i++){
			var el = this[i];
			if(resultArray.valueIndex(el) === -1) resultArray.push(el);
		}
	}
	return resultArray;
}
Array.prototype.valueIndex=function(pval){
 var idx = -1;
 if(this==null || this==undefined || pval==null || undefined){
 } else {
     for(var i=0;i<this.length;i++){
         if(this[i]==pval){
             idx=i;
             break;
         }
     }
 }
 return idx;
}