﻿/*
 * common.js
 */

$(document).ready(function() {
	responsive(); //사이즈 조절
	pageInit(); //페이지 기본 라이브러리 실행

	$(document).on("click",".btn_modalOpen",function(e){
		e.preventDefault();
		var targetModal = $(this).attr("href");
		modalOpen(targetModal);
	});
	$(document).on("click","#overlay, .btn_modalClose",function(){
		modalClose();
	});

	//$("#lnb").css("height",$(window).height()-52);
});

$(window).resize(function(){
	responsive();
});

function responsive(){
}
function pageInit(){
	addInputHandler({input:$(".onlyNum"),dataType:"N",maxlength:7});
	addInputHandler({input:$(".onlyEng"),dataType:"AP"});
	addInputHandler({input:$(".engNum"),dataType:"AN"});
	addInputHandler({input:$(".onlyHan"),dataType:"HA"});
	useDatepicker();
	useFileBtn();
	useTab();
	useWordLength();
	//subTab();

	$("label").each(function(){
		$(this).removeClass("linked");
		if($(this).find("input[type='radio']").length > 0 || $(this).find("input[type='checkbox']").length > 0){
			$(this).addClass("linked");
		}
	});
}
function addInputHandler(conditions){
	var $input = conditions.input;
	var dataType = conditions.dataType;
	var eventType = conditions.eventType;
	if((!$input) || (!dataType)){
		throw {error:"NotEnoughArguments", errorMsg:"required argument is missing " +((!$input)?" target input element":" dataType")}
		return;
	}
	if((!eventType)){
		eventType = "keyup";
	}
	var handlerFunc = conditions.handler;
	if((!handlerFunc)){ 
		handlerFunc = function(event){
			var regEx = null;
			if(dataType == "N"){
				regEx = /[^0-9]/gi;
			}else if(dataType == "AP"){
				regEx = /[^a-z]/gi;
			}else if(dataType == "AN"){
				regEx = /[^a-z0-9]/gi;
			}else if(dataType == "HA"){
				regEx = /[a-z0-9]/gi;
			}else{
				throw {error:"IlregalDataType", errorMsg:"dataType("+dataType+") is incorrect"}     
			}
			remainOnlyTargetValue(regEx, $input,event);
			//return true;
		};  // end of handlerFunc
	} // end of if to check handlerFunc
	$input.on(eventType,handlerFunc);
	if(conditions.maxlength){
		$input.attr("maxlength",conditions.maxlength);
	}
}
function remainOnlyTargetValue(regEx, $input, event) {
	if((!(event.keyCode >= 34 && event.keyCode <= 40)) && event.keyCode != 16){
		var inputVal = $input.val();
		if(regEx.test(inputVal)){
			event.preventDefault ? event.preventDefault() : event.returnValue = false;
			$input.val(inputVal.replace(regEx,''));
		}
	}
}
function useWordLength(){
	$("textarea").each(function(){
		var textName = "none";
		if($(this).attr("name")){
			textName = $(this).attr("name");
		}
		if($(this).attr("data-limitByte")){
			var limitByte = parseInt($(this).attr("data-limitByte"));
			if($("wordCount_"+textName).length == 0){
				$(this).after('<span id="wordCount_'+textName+'" class="wordCount"><b>0</b> / '+limitByte+' Byte</span>');
			}
			$(this).keyup(function(){
				textName = $(this).attr("name");
				limitByte = parseInt($(this).attr("data-limitByte"));
				var totalByte = 0;
				var limitLength = 0;
				var message = $(this).val();
				for(var i =0; i < message.length; i++){
					var currentByte = message.charCodeAt(i);
					if(currentByte > 128) totalByte += 2;
					else totalByte++;
					if(totalByte > limitByte){
						limitLength = i;
						$(this).val(message.substring(0,limitLength));
						totalByte = limitByte;
						break;
						return;
					}
				}
				$("#wordCount_"+textName+" b").text(totalByte);
			});
		}
    });
}
function useDatepicker(){
	var holidayData = [
		{'mmdd':'1-1','title':'신정'},
		{'mmdd':'3-1','title':'3.1절'},
		{'mmdd':'5-5','title':'어린이날'},
		//{'mmdd':'5-10','title':'석가탄신일'},
		{'mmdd':'6-6','title':'현충일'},
		{'mmdd':'8-15','title':'광복절'},
		{'mmdd':'10-3','title':'개천절'},
		{'mmdd':'10-9','title':'한글날'},
		{'mmdd':'12-25','title':'크리스마스'}
	];

	$(".useDatepicker").each(function(){
		var minDate = $(this).attr("data-minDate");
		var maxDate = $(this).attr("data-maxDate");
		var dateFormat = "yy-mm-dd";
		if($(this).attr("data-format")) dateFormat = $(this).attr("data-format");
		$(this).css({"width":"105px"}).datepicker({
			prevText: '이전 달',
			nextText: '다음 달',
			monthNames: ['01','02','03','04','05','06','07','08','09','10','11','12'],
			monthNamesShort: ['01','02','03','04','05','06','07','08','09','10','11','12'],
			dayNames: ['일요일','월요일','화요일','수요일','목요일','금요일','토요일'],
			dayNamesShort: ['일','월','화','수','목','금','토'],
			dayNamesMin: ['일','월','화','수','목','금','토'],
			dateFormat: dateFormat,
			showMonthAfterYear: true,
			yearSuffix: ' ',
			yearRange: 'c-50:c+30',
			minDate: minDate,
			maxDate: maxDate,
			changeMonth: true,
			changeYear: true,
			beforeShowDay: function(date){
				var holidayCheck = false;
				var mmdd = (date.getMonth() + 1)+"-"+date.getDate();
				for(var i=0; i<holidayData.length; i++){
					if(holidayData[i].mmdd == mmdd){
						holidayCheck = true;
						return [true, "date-holiday", holidayData[i].title];
						break;
					}
				}
				if(holidayCheck == false){
					return [true, ""];
				}
			},
			onSelect: function(selectedDate){
			},
			onClose: function(selectedDate){
				if(this.id == "dateFrom" ) {
					if(selectedDate != "" && $("#dateTo").val() != ""){
						if(selectedDate >= $("#dateTo").val()){
							alert("시작날짜는 종료날짜보다 작아야 합니다.");
							$("#dateFrom").val("");
							return;
						}
					}
				}else if(this.id == "dateTo" ) {
					if(selectedDate != "" && $("#dataFrom").val() != ""){
						if($("#dateFrom").val() >= selectedDate){
							alert("종료날짜는 시작날짜보다 커야 합니다.");
							$("#dateTo").val("");
							return;
						}
					}
				}
			}
		});
	});
	
}
function useFileBtn(){
	$("input[type='file']").each(function(){
		var file_name = $(this).attr("id");
		$(this).after('<span id="for_'+file_name+'"><input type="text" class="w120" value=""> <a href="#" class="btn_inline btn_search for_fileBtn">찾아보기</a></span>');
		$(this).hide();
		$(this).change(function(){
			$("#for_"+file_name+" input[type='text']").val($(this).val());
		});
	});
	$(".for_fileBtn").click(function(){
		var id = $(this).parent().attr("id").replace("for_","");
		$("#"+id).click();
	});
}
function useTab(){
	$(".tabBar").each(function(){
		if(!$(this).hasClass("notUsed")){
			var tabBar = $(this);
			if(tabBar.find(".active").length == 0){
				tabBar.find("li").eq(0).not(".notUsed").addClass("active");
				tabBar.siblings(".tabPage").eq(0).addClass("active");
			}
		}
	});
	$(".tabBar li a").on("click",function(e){
		var tabBar = $(this).parent().parent();
		var tabLi = $(this).parent();
		var tabLiAll = $(this).parent().parent().children("li");
		var tabNo = tabLi.index();
		var tabPageAll = tabBar.parent().children(".tabPage");
		var tabPage = tabPageAll.eq(tabNo);
		if(!tabBar.hasClass("notUsed")){
			if(!tabPage.hasClass("active") && tabPage.length > 0){
				tabPageAll.removeClass("active");
				tabPage.addClass("active");
				tabLiAll.removeClass("active");
				tabLi.addClass("active");
				e.preventDefault();
			}
		}
	});
}

//tap
function subTab(){
	$(".tabBar_type2 > li").click(function(){
		$(".tabBar_type2 > li").removeClass("active");
		$(this).addClass("active");
	});
}
	


function loadingStart(){
	$("body").append('<div id="loading"><div></div></div>');
}

/*Cookie*/
function GetCookie(cookieName){
	var search = cookieName+"=";
	var cookie = document.cookie;
	if(cookie.length > 0){
		startIndex = cookie.indexOf(cookieName);
		if(startIndex != -1){
			startIndex += cookieName.length;
			endIndex = cookie.indexOf(";", startIndex);
			if(endIndex == -1) endIndex = cookie.length;
			return unescape(cookie.substring(startIndex + 1, endIndex));
		}else{
			return false;
		}
	}else{
		return false;
	}
}
function SetCookie(cookieName, cookieValue, expireDate){
	var today = new Date();
	today.setDate(today.getDate() + parseInt(expireDate));
	document.cookie = cookieName+"="+escape(cookieValue)+"; path=/; expires="+today.toGMTString()+";";
}
function DelCookie(cookieName){
	var expireDate = new Date();
	expireDate.setDate(expireDate.getDate() - 1);
	document.cookie = cookieName+"= "+"; expires="+expireDate.toGMTString()+"; path=/";
}

function modalOpen(id){
	$(window).scrollTop(0);
	$(id).fadeIn(100);
	$("#overlay").fadeIn(100);
}
function modalClose(){
	$(".modalWrap").fadeOut(100);
	$("#overlay").fadeOut(100);
}