﻿//jQuery Ajax 오류 처리 함수
function ajaxError(type, stat, msg) {
	alert("시스템 오류로 요청 처리 실패\n - errorType : " + type + "\n - status : " + stat + "\n - errMsg : " + msg);
}


//삭제시 사용자 확인용
function delCheck() {
	return confirm("정말 삭제하시겠습니까?");
}



//Highslide 레이어팝업 오픈
function layerPop(url, w, h, objType, position) {
	if (!objType) { objType = "iframe"; }
	if (!position) { position = "center"; }

	var anc = $(document.createElement("a"));
	anc.appendTo(document);
	anc.attr("href", url);
	anc.focus(function () {
		var option = {
			objectType: objType
			, outlineType: null
			, width: w
			, align: position
		}

		if (h) {
			option.height = h;
		}

		hs.htmlExpand(this, option);
	});

	anc.focus();
	anc.remove();
}


//Highslide 히든레이어 팝업형태로 오픈
function showHiddenLayer(id, w, h, position) {

	$("#" + id).show();
	return;
	//IE8 관련 정리될때까지 보류
	
	if (!position) { position = "center"; }

	var anc = $(document.createElement("a"));
	anc.appendTo(document);
	anc.attr("href", "#");
	anc.focus(function () {
		return hs.htmlExpand(this, { contentId: id, width: w, height: h, align: position });
	});

	anc.focus();
	anc.remove();
}


//모달 Ajax 레이어 팝업 띄우기
function OpenModal(url, params, title, maxWidth, maxHeight) {
	if (!maxWidth) maxWidth = 600;
	if (!maxHeight) maxHeight = 400;

	$.get(url, params, function (data, textStatus, XMLHttpRequest) {
		win = $.modal({
			content: data
				, title: title
				, maxWidth: maxWidth
				, maxHeight: maxHeight
				, resizable: false
		});
	});

	return false;
}

//모달 Iframe 레이어 팝업 띄우기
function OpenIframeModal(url, title, maxWidth, maxHeight) {
	if (!maxWidth) maxWidth = 600;
	if (!maxHeight) maxHeight = 400;

	win = $.modal({
		content: "<iframe frameborder='0' src='" + url + "' style='width:" + maxWidth + "px; height:" + maxHeight + "px;'></iframe>"
			, title: title
			, width: maxWidth
			, maxWidth: maxWidth
			, height: maxHeight
			, maxHeight: maxHeight
			, resizable: false
			, scrolling: false
	});

	return false;
}


//페이지 Get방식 이동하기 (주로 검색용)
function SearchBtn(paramStr) {
	var urlArr = location.href.split("//")[1].split("?")[0].split("#")[0].split("/");
	var url = "";
	$(urlArr).each(function (i) { if (i != 0) url += "/" + this });
	var querystring = "";
	var params = paramStr.split(",");

	for (i = 0; i < params.length; i++) {
		if (params[i].length > 0) {
			querystring += querystring.length == 0 ? "?" : "&";

			querystring += params[i] + "=";
			querystring += encodeURIComponent($("#" + params[i]).val());
		}
	}

	location.href = url + querystring;
}


//엑셀파일 다운로드
//hiddenframe으로 정해진 페이지호출
function GetExcelFile(querystrings, type) {
	hiddenfrm.location.href = "/Services/GetExcel.ashx" + querystrings + "&type=" + type;
}


//입력된 id값을 가지는 객체 숨기기
function HideObj(id) {
	$("#" + id).hide();
}






/**********************************  객체 값 조작/판독 함수 모음  ***************************************/

//-----------------------------------------
//	문자열의 Byte길이 반환
//
//	- str [string] [null] : 길이를 체크할 문자열
//-----------------------------------------
function GetBytes(str) {
	var len = 0;

	if (str == null)
		return 0;

	for (var i = 0; i < str.length; i++) {
		var c = escape(str.charAt(i));
		if (c.length == 1) len++;
		else if (c.indexOf("%u") != -1) len += 2;
		else if (c.indexOf("%") != -1) len += c.length / 3;
	}

	return len;
}


//-----------------------------------------
//	문자열 Byte길이로 자르기
//
//	- str		[string]	[null]			: 잘라낼 원본 문자열
//	- limit		[int]		[null]			: 잘라낼 문자열 길이
//	- deadend	[string]	[""]			: 잘라낸 후 붙여줄 문자열
//	- limitType	[string]	["byte"/length]	: 잘라낼 문자열 길이 추출방식
//-----------------------------------------
function CutString(str, limit, deadend, limitType) {
	var tmpStr = str;
	var byte_count = 0;
	var len = str.length;
	if (!deadend) deadend = "";
	if (!limitType) limitType = "byte";

	if (limitType == "byte") {
		for (i = 0; i < len; i++) {
			byte_count += GetBytes(str.charAt(i));

			if (byte_count == limit - 1) {
				if (GetBytes(str.charAt(i + 1)) == 2) {
					tmpStr = str.substring(0, i + 1);
					dot = deadend;
				}
				else {
					if (i + 2 != len) dot = deadend;
					tmpStr = str.substring(0, i + 2);
				}

				break;
			}
			else if (byte_count == limit) {
				if (i + 1 != len) dot = deadend;
				tmpStr = str.substring(0, i + 1);
				break;
			}
		}

		
	}
	else {
		tmpStr = str.substring(0, limit) + (str.length > limit ? deadend : "");
	}

	return (tmpStr + dot);
}


//-------------------------------------------
//	YYYY-MM-DD 형식 문자열을 날짜로 치환하기
//
//	- str	[string]	[null] : 치환할 문자열
//-------------------------------------------
function ToDate(str) {
	// [-]가 두개 들어있지 않을 경우 null 리턴
	var strArr = str.split("-");
	if (strArr.length != 3) return null;

	var returnDate = new Date();
	returnDate.setYear(parseInt(strArr[0]) - 1);
	returnDate.setMonth(parseInt(strArr[1], 10) - 1);
	returnDate.setDate(parseInt(strArr[2], 10));

	return returnDate;
}


//-------------------------------------------
//	Date객체를 YYYY-MM-DD 형식 문자열로 치환하기
//
//	- date		[date]		[now] : 치환할 날짜값
//	- devider	[string]	["-"] : 년,월,일 사이 구분 문자열
//-------------------------------------------
function GetYYYYMD(date, devider) { 
	//날짜 객체가 맞다고 가정하고 진행한다.
	try {
		
		if (!devider) devider = "-";

		return date.getFullYear() + devider + SetStringLength((date.getMonth() + 1), 2, "0") + devider + SetStringLength(date.getDate(), 2, "0");
	}
	catch (e) {
		alert("[시스템 오류]\n데이터 형식이 잘못되었습니다.");
		throw e;
	}
}


//-------------------------------------------
//	Date객체를 YY-MM-DD 형식 문자열로 치환하기
//
//	- date		[date]		[now] : 치환할 날짜값
//	- devider	[string]	["-"] : 년,월,일 사이 구분 문자열
//-------------------------------------------
function GetYYYYMD(date, devider) {
	//날짜 객체가 맞다고 가정하고 진행한다.
	try {

		if (!devider) devider = "-";

		return date.getFullYear().toString().substring(2, 4) + devider + SetStringLength((date.getMonth() + 1), 2, "0") + devider + SetStringLength(date.getDate(), 2, "0");
	}
	catch (e) {
		alert("[시스템 오류]\n데이터 형식이 잘못되었습니다.");
		throw e;
	}
}


//-------------------------------------------
//	원하는 길이만큼 입력된 값의 앞뒤에 정해진 문자열을 붙여 반환
//
//	- input		[string]	[null]			: 원본 문자열
//	- length	[int]		[0]				: 최종적으로 반환할 길이. 원본문자열 길이보다 작으면 효과없음
//	- addChar	[string]	[null]			: 앞뒤로 붙여줄 문자. 여러자리 문자열을 입력해도 최초 1문자만 사용한다.
//	- addFront	[bool]		["true"/false]	: 추가 문자열을 붙여줄 방향
//-------------------------------------------
function SetStringLength(input, length, addChar, addFront) {
	
	//문자열 이외의 값이 들어올 수도 있으므로 일단 문자열화
	var returnStr = input.toString();

	//원본길이가 목표길이보다 길면 그냥 반환
	if (input.length >= length) return input;

	for (var i = input.length; i < length; i++) { 
		//false로 지정된 것 이외에는 무조건 true로 인식
		if (addFront != false) {
			returnStr = addChar + returnStr;
		}
		else {
			returnStr += addChar;
		}
	}

	return returnStr;
}


//-------------------------------------------
//	입력된 날짜 값의 요일 값 반환
//
//	- date	[string]	[null]			: 날짜로 치환 가능한 문자열. 치환불가능한 문자열일경우 null반환
//	- lan	[string]	["kr"/en]		: 변환할 언어. 일단 국문,영문만 지원
//-------------------------------------------
function GetWeekday(date, lan) {
	try {
		var weekday = ToDate(date).getDay();

		if (!lan) lan = "kr";

		if (lan == "kr") {
			switch (weekday) {
				case 0:
					return "일";
				case 1:
					return "월";
				case 2:
					return "화";
				case 3:
					return "수";
				case 4:
					return "목";
				case 5:
					return "금";
				case 6:
					return "토";
			}
		}
		else if (lan == "en") {
			switch (weekday) {
				case 0:
					return "Sun";
				case 1:
					return "Mon";
				case 2:
					return "Tue";
				case 3:
					return "Wed";
				case 4:
					return "Thu";
				case 5:
					return "Fri";
				case 6:
					return "Sat";
			}			
		}
	}
	catch (e) {
		alert("[시스템 오류]\n입력된 문자열 형식이 잘못되었습니다.\n")
		throw e
	}
}




/**********************************  쿠키 관련 함수 모음 ***************************************/

//-------------------------------------------
//	저장된 쿠키값을 키-값 쌍으로 구분된 다차원배열형태로 반환
//-------------------------------------------
function GetCookieObj() {
	var cookieStr = document.cookie;
	var cookies = cookieStr.split(";");

	var objStr = '{';


	for (var i = 0; i < cookies.length; i++) {
		//이름-값 쌍을 이루는 경우 진행
		if (cookies[i].indexOf("=") != -1) {
			objStr += i == 0 ? '' : ',';

			//다차원배열일경우
			var cookieArr = cookies[i].split('=');
			var key = $.trim(cookieArr[0].replace(":", ""));
			var values = "";
			for (var x = 1; x <= cookieArr.length; x++) {
				values += x == 1 ? "" : "=";
				values += cookieArr[x];
			}

			if (values.indexOf("&") != -1) {
				objStr += '"' + key + '" : {';

				var valuesArr = values.split('&');
				for (var j = 0; j < valuesArr.length; j++) {
					objStr += j == 0 ? '' : ',';

					objStr += '"' + $.trim(valuesArr[j].split('=')[0].replace(":", "")) + '" : "' + valuesArr[j].split('=')[1] + '"';
				}

				objStr += '}';
			}
			//2차원배열일경우
			else {
				objStr += '"' + $.trim(cookies[i].split('=')[0].replace(":", "")) + '" : "' + cookies[i].split('=')[1] + '"';
			}
		}
	}

	objStr += '}';

	return $.parseJSON(objStr);
}

//-------------------------------------------
//	쿠키값 가져오기 
//
//	- name	[string]	[null]			: 값을 가져올 쿠키명
//	- key	[string]	[null]			: 쿠키 키
//-------------------------------------------
function GetCookie(name, key) {
	var cookie = GetCookieObj();

	try {
		if (!key) {
			//기본 이름으로 검색이 되지 않을 경우 도메인명 하위로 검색한다.
			var returnStr = eval("cookie." + name);
			if (!returnStr) {
				returnStr = eval("cookie." + location.host.replace(/\./gi, "_") + "." + name);
			}

			return returnStr;
		}
		else {
			return eval("cookie." + name + "." + key);
		}
	}
	catch (e) {
		return "";
	}
}


//-------------------------------------------
//	쿠키값 설정하기
//
//	- name			[string]	[null]	: 쿠키명
//	- value			[string]	[null]	: 쿠키값
//	- expiredays	[int]		[null]	: 만료시간까지 일 수	
//-------------------------------------------
function SetCookie(name, value, expiredays) {
	var todayDate = new Date();
	todayDate.setDate(todayDate.getDate() + expiredays);
	document.cookie = name + "=" + escape(value) + "; path=/; expires=" + todayDate.toGMTString() + ";";
}
