// 인터넷 열린학교 자바스크립트 모음

/** ------------------------------------------------------------------------------------------------
 OnCheck(선택체크박스, 전체체크박스배열) - 전체체크박스의 배열을 선택체크박스에
 checked 값으로 모두 바꾼다.
 p.s 일괄 선택, 해제
 ------------------------------------------------------------------------------------------------**/
function OnCheck(pIntId, pStrId){
	var length = document.getElementsByName(pStrId).length;
	var flag = document.getElementById(pIntId).checked;
	for(i=0;i<length;i++){
		document.getElementsByName(pStrId)[i].checked = flag;
	}
}

/** ------------------------------------------------------------------------------------------------
 gotoURL (URL, type)
페이지를 이동한다.
	type 값에 따라 target을 결정함
	type 값이 누락되어서 undefined 이면 현재창으로 이동하고
	type 값이 "_parent" 또는 "parent" 이면 상위로 이동
	type 값이 "_top" 또는 "top" 이면 최상위로 이동
 ------------------------------------------------------------------------------------------------**/
function gotoURL(url, type) {
	if (type == undefined) {
		location.href = url;
	} else if ((type == "_parent") || (type == "parent")) {
		parent.location.href = url;
	} else if ((type == "_top") || (type == "top")) {
		top.location.href = url;
	} else {
		window.open(url, type, "status=yes");
	}
	return;
}

/** ------------------------------------------------------------------------------------------------
openWindow (URL, 가로, 세로, 리사이즈여부(yes/no), 스크롤여부( yes/no), 새창이름)
 URL을 새창으로 정해진 사이즈로 띄운다 (정가운데에)
 ------------------------------------------------------------------------------------------------**/
function openWindow(strURL, intWidth, intHeight, blnResize, blnScroll, windowName)
{
	var left = (screen.width - intWidth) / 2;
	var top = (screen.height - intHeight) / 2;
	var settings = "width=" + intWidth;
		settings = settings + ", height=" + intHeight;
		settings = settings + ", left=" + left;
		settings = settings + ", top=" + top;
		settings = settings + ", scrollbars=" + blnScroll;
		settings = settings + ", resizable=" + blnResize;
		settings = settings + ",status=yes"

	var win = window.open(strURL, windowName, settings);
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

/** ------------------------------------------------------------------------------------------------
openWindowPoint (URL, 가로, 세로, 리사이즈여부(yes/no), 스크롤여부( yes/no), 새창이름, 위, 좌)
 URL을 새창으로 정해진 사이즈로 띄운다
 ------------------------------------------------------------------------------------------------**/
function openWindowPoint(strURL, intWidth, intHeight, blnResize, blnScroll, windowName, intTop, intLeft)
{
	var left = (screen.width - intWidth) / 2;
	var top = (screen.height - intHeight) / 2;
	var settings = "width=" + intWidth;
		settings = settings + ", height=" + intHeight;
		settings = settings + ", left=" + intLeft;
		settings = settings + ", top=" + intTop;
		settings = settings + ", scrollbars=" + blnScroll;
		settings = settings + ", resizable=" + blnResize;
		settings = settings + ",status=yes"

	var win = window.open(strURL, windowName, settings);
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

/** ------------------------------------------------------------------------------------------------
openWindowSubmit (URL, 가로, 세로, 리사이즈여부(yes/no), 스크롤여부( yes/no), Target, form)
 URL을 새창으로 정해진 사이즈로 띄운다 (정가운데에)
 ------------------------------------------------------------------------------------------------**/
function openWindowSubmit(strURL, intWidth, intHeight, blnResize, blnScroll, pTarget, pObjForm)
{
	var left = (screen.width - intWidth) / 2;
	var top = (screen.height - intHeight) / 2;
	var settings = "width=" + intWidth;
		settings = settings + ", status=yes, height=" + intHeight;
		settings = settings + ", left=" + left;
		settings = settings + ", top=" + top;
		settings = settings + ", scrollbars=" + blnScroll;
		settings = settings + ", resizable=" + blnResize;

	var win = window.open("", pTarget, settings);

	pObjForm.action = strURL;
	pObjForm.target = pTarget;
	pObjForm.submit();

	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

 /** ------------------------------------------------------------------------------------------------
	롤오버만들기 2
		두개의 이미지를 동일한 이름으로 하고 끝을 a로 구분한다. (gif파일에만 적용)
		그리고 이미지 태그에 다음을 추가
		 onMouseOver="img_act('a');" onMouseOut="img_inact('a');"
 ------------------------------------------------------------------------------------------------**/
function img_act(type) {
	var imgId;
	var strSrc;
	imgId = window.event.srcElement;
	strSrc = imgId.src;

	imgId.src = strSrc.substring(0, strSrc.length - 4) + type + ".gif";
}

function img_inact(type) {
	var imgId;
	var strSrc;
	imgId = window.event.srcElement;
	strSrc = imgId.src;
	imgId.src = strSrc.substring(0, strSrc.length - (type.length + 4)) + ".gif";
}

 /** ------------------------------------------------------------------------------------------------
	쿠키제어 스크립트
 ------------------------------------------------------------------------------------------------**/
 function openPopup(cookiename, url, winname, w, h, blnResize, blnScroll) {
	var openok = getCookie(cookiename)
	if ( openok == "no" ) {
	} else {
		openWindow(url, winname, w, h, blnResize, blnScroll);
	}
	return false;
}

function getCookie(name) {
	var prefix = name + "=";

	var cookieStartIndex = document.cookie.indexOf(prefix);
	if (cookieStartIndex == -1) return null;

	var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
	if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
	return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

function setCookie (cookiename, value, expiredays)
{
        var todayDate = new Date();
        todayDate.setDate( todayDate.getDate() + expiredays );
        document.cookie = cookiename + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}

function setCookieCloseWindow(cookiename)
{
        setCookie(cookiename, "no" , 1);
		window.close()
}

 /** ------------------------------------------------------------------------------------------------
	날짜출력 스크립트 "~월 ~일" 형태로 브라우저에 출력
	<script language="javascript">printDate();</script>
	로 사용
 ------------------------------------------------------------------------------------------------**/
function printDate() {
	var now = new Date();
	document.write(now.getMonth() + 1, "월 ", now.getDate(), "일");
}

 /** ------------------------------------------------------------------------------------------------
	요일출력 스크립트 "일"~"토" 까지 요일의 첫자를 출력
	<script language="javascript">printWeek();</script>
	로 사용
 ------------------------------------------------------------------------------------------------**/
function printWeek() {
	var now = new Date();
	var strWeekday;
	if (now.getDay() == 0) {
		strWeekday = "일";
	} else if (now.getDay() == 1) {
		strWeekday = "월";
	} else if (now.getDay() == 2) {
		strWeekday = "화";
	} else if (now.getDay() == 3) {
		strWeekday = "수";
	} else if (now.getDay() == 4) {
		strWeekday = "목";
	} else if (now.getDay() == 5) {
		strWeekday = "금";
	} else if (now.getDay() == 6) {
		strWeekday = "토";
	}
	document.write(strWeekday);
}

 /** ------------------------------------------------------------------------------------------------
 * 체크박스 모두선택시 호출
 * 인수: Checkbox 배열 객체
 ------------------------------------------------------------------------------------------------**/
function onSelectAll(arrChks)
{
	try
	{
		var blnAll = true;							// 모두 선택되어 있는지 여부
		for (var i = 0; i < arrChks.length; i++)
		{
			if (!arrChks[i].checked)
			{
				blnAll = false;
				break;
			}
		}
		doSelectAll(arrChks, !blnAll);
	}
	catch(e)
	{
		e.message = 'onSelectAll(): ' + e.message;
		alert(e.message);
	}
}

 /** ------------------------------------------------------------------------------------------------
 * 체크박스를 모두 선택 또는 미선택 처리
 * 인수: 체크박스 배열객체, 부울값
 ------------------------------------------------------------------------------------------------**/
function doSelectAll(arrChks, blnChk)
{
	try
	{
		if(arrChks)
		{
			if(arrChks.length)
			{
				for (var i = 0; i < arrChks.length; i++)
					arrChks[i].checked = blnChk;
			}
			else
			{
				arrChks.checked = blnChk;
			}
		}
	}
	catch(e)
	{
		e.message = 'doSelectAll(): ' + e.message;
		throw e;
	}
}

 /** ------------------------------------------------------------------------------------------------
 * 문자 1자리를 제거
 * 인수: 원본 문자열, 삭제할 문자
 ------------------------------------------------------------------------------------------------**/
function removeChar(strSrc, chr)
{
	if (chr.length > 1)
		return strSrc;

	strSrc = new String(strSrc);
	var strTemp = '';
	if (strSrc != null)
	{
		for (var i = 0; i < strSrc.length; i++)
		{
			var c = strSrc.substring(i, i + 1);
			if (c != chr)
				strTemp = strTemp.concat(c);
		}
	}
	return strTemp;
}

 /** ------------------------------------------------------------------------------------------------
 * 이미지사이즈대로 윈도우창 조절
 * 인수: 이미지경로
 ------------------------------------------------------------------------------------------------**/
function ShowImage(path){
	imgFile = new Image();
	imgFile.src = path ;
	var x1 = imgFile.width;
	var y1 = imgFile.height;
	var winX = x1 + 10;
	var winY = y1 + 30;
	var limitX = screen.availWidth;
	var limitY = screen.availheight;
	if (x1 > limitX) {
		window.moveTo(0, 0);
		window.resizeTo(limitX, limitY);
	}
	else {
		window.moveTo(200, 200);
		window.resizeTo(winX, winY);
	}
}

 /** ------------------------------------------------------------------------------------------------
 * Admin Center Page 에서 기본 index 수정 가능한지 쿠키 제어
 * 인수: 영문 인덱스 타이틀 (info, class....)
 ------------------------------------------------------------------------------------------------**/
 function changeMainIndexCookie(title) {
	 var curCookie = getCookie(title);
	 if (curCookie == "Y") {
		setCookie (title, "", 30);
	 } else {
		setCookie (title, "Y", 30);
	 }
 }

  /** ------------------------------------------------------------------------------------------------
 * Admin Center Page 에서 기본 index 수정 가능한지 쿠키를 초기화
 * 인수: 모두 끌 것인지 (Y) 모두 켤 것인지 (N)
 ------------------------------------------------------------------------------------------------**/
 function initMainIndexCookie(bit) {
	setCookie ("Info", bit, 30);
	setCookie ("Kids", bit, 30);
	setCookie ("Class", bit, 30);
	setCookie ("Teachers", bit, 30);
	setCookie ("Affairs", bit, 30);
	setCookie ("Finance", bit, 30);
	setCookie ("Material", bit, 30);
 }



/** ------------------------------------------------------------------------------------------------
openPopImage (이미지경로)
이미지경로의 그림을 새창으로 정중앙에 크기조절하여 띄운다
IMG tag에서 onClick='openPopImage(this)' 와 같은 형태로 삽입
 ------------------------------------------------------------------------------------------------**/
function openPopImage(target_img)
{
	var openw, openh
    var openImg;
	var openUrl;
	var yesno;
	var feature;
	var scrWidth = screen.availWidth - 10;
	var scrHeight = screen.availHeight - 10;
	var posLeft;
	var posTop;
	var newWidth;
	var newHeight;

    openImg = new Image();
	if (target_img.src == undefined) {
		openImg.src = target_img;
	} else {
		openImg.src = target_img.src;
	}
    openw = openImg.width;
    openh = openImg.height;


    if (openw > scrWidth || openh > scrHeight)
    {
        if(openw > openh)
        {
            if(openw > scrWidth)
                newWidth = scrWidth;
            else
                newWidth = openw;
	            newHeight = Math.round((openh*newWidth)/openw);
        }
        else
        {
            if(openh > scrHeight)
                newHeight = scrHeight;
            else
                newHeight = openh;
	            newWidth = Math.round((openw*newHeight)/openh);
        }
    } else {
		newWidth = openw;
		newHeight = openh;
	}

//	posLeft = (scrWidth - newWidth) / 2;
//	posTop = (scrHeight - newHeight) / 2;
	posLeft = 0;
	posTop = 0;

	feature = 'toolbar=no, location=no, status=no, menubar=no, scrollbars=no, resizable=no, width=' + scrWidth + ',height=' + scrHeight + ', left=' + posLeft + ', top=' + posTop;
	openUrl = "/app/include/HtmlEditor/photoview.asp?pic=" + openImg.src + "&width=" + newWidth + "&height=" + newHeight;
	window.open(openUrl, 'pic', feature);
}


/**
* string String::cut(int len)
* 글자를 앞에서부터 원하는 바이트만큼 잘라 리턴합니다.
* 한글의 경우 2바이트로 계산하며, 글자 중간에서 잘리지 않습니다.
*/
String.prototype.cut = function(len) {
	var str = this;
	var l = 0;
	for (var i=0; i<str.length; i++) {
		l += (str.charCodeAt(i) > 128) ? 2 : 1;
		if (l > len) return str.substring(0,i);
	}
	return str;
}

/**
* bool String::bytes(void)
* 해당스트링의 바이트단위 길이를 리턴합니다. (기존의 length 속성은 2바이트 문자를 한글자로 간주합니다)
*/
String.prototype.bytes = function() {
	var str = this;
	var l = 0;
	for (var i=0; i<str.length; i++) l += (str.charCodeAt(i) > 128) ? 2 : 1;
	return l;
}

/** ------------------------------------------------------------------------------------------------
* Textarea 쓰인 글자 수 제한 사용자에게 보여주기
* 인수: TextArea, 최대글자수, 현재위치
* Ex : <textarea onChange="CheckLen(this, 400, '설명');" OnKeyUp="saveCurrentPos(this);CheckLen(this, 400, '설명');">
* <span id='count'>(0/400)</span>
------------------------------------------------------------------------------------------------**/
function CheckLen(pTextarea, pMaxLength, pMsg){
	var textValue = pTextarea.value;
	var textByte = textValue.bytes();

	count.innerHTML = '(' + textByte + '/' + pMaxLength + ' Byte)';


    if (textByte> pMaxLength){
		alert(pMsg + "는 " + pMaxLength + "자까지만 쓰실 수 있습니다.");
		pTextarea.value = pTextarea.value.cut(pMaxLength);
		count.innerHTML = '(' + pTextarea.value.bytes() + '/' + pMaxLength + ' Byte)';
		return;
    }

}


/** ModalessDialog open **/
function ModalessDialog( url, args, width, height)
{
	var env_options = "dialogHeight: " + height + "px; dialogWidth: " + width + "px;  edge: Raised; center: Yes; help: No; scroll: No; resizable: No; status: No;";
	window.showModelessDialog( url, args, env_options);
}

function resizeImage(Maxwidth)
{
	var imgs=document.all.tags('img');
	if (imgs == null) return;

	var state = true;

	for(i=0;i<imgs.length;i++)
	{
		width = parseInt(imgs[i].width);
		height = parseInt(imgs[i].height);

		if (width <= 1 && height <= 1)
		{
			state=!state;
		}

		if (state && width > parseInt(Maxwidth) ) // 이미지가  Maxwidth 보다 크면 리사이징
		{
			imgs[i].width = Maxwidth;
			imgs[i].height = (Maxwidth/width) * height;
		}
	}
}

/** Iframe Cursor Tail Script Start '05-09-10 Chocomug**/
function moveInnerMouseCursor(){
	parent.document.all['Mouse'].style.left=event.clientX+290;
	parent.document.all['Mouse'].style.top=event.clientY+114;
}
function innerMouseFollow() {
	if (document.all) moveInnerMouseCursor();
}
function initInnerCursorTail() {
	if (!(parent.document.getElementById('Mouse') == null)) {
		document.onmousemove = innerMouseFollow;
	}
}
initInnerCursorTail();
/** Iframe Cursor Tail Script End **/


/** 팝업 사이즈 조절하는거.. **/
function onPopupResize()
{
	window.moveTo(100,100);
	window.resizeTo(document.body.scrollWidth + 10, document.body.scrollHeight + 69);
}

/** 글자제한하는거.. **/
/** obj는 현재 object, mexLen은 영문 최대값, pText는 메지시 **/
var oldText;
function CheckLenText(obj, maxLen, pText) {
    var temp;
    var memocount = 0;
    len = obj.value.length;

    for(k=0;k<len;k++){
	    temp = obj.value.charAt(k);
	    if(escape(temp).length > 4)
		    memocount += 2;
	    else
		    memocount++;
    }

    if (memocount > maxLen) {
		alert(pText + " 한글"+ (maxLen/2) +"자(영문"+ maxLen +"자)까지 가능합니다.");
		obj.value = oldText;
		return;
    }
    else {
		oldText = obj.value;
    }
}

/** 이미지 온오버.. **/
/** pBool = true : mouseover **/
/** pBool = false : mouseout **/
function onImgMouseEvent(pObj,pBool)
{
	if(!pObj) return;

	var arrSrc = pObj.src.split("/");
	var imgURL = pObj.src.replace(arrSrc[arrSrc.length - 1], "");

	var imgName = arrSrc[arrSrc.length - 1].split(".")[0].split("_");
	var imgExt  = arrSrc[arrSrc.length - 1].split(".")[1];

	var imgName2 = "";

	if(imgName)
	{
		for(n=0; n< imgName.length - 1; n++)
		{
			imgName2 += imgName[n] + "_";
		}
	}

	//alert(arrSrc[arrSrc.length - 1].split(".")[0] + " - " + imgName2 + " - " + imgName + " - " + imgName.length);

	if(pBool)
		imgName2 = imgName2 + "on." + imgExt;
	else
		imgName2 = imgName2 + "off." + imgExt;

	pObj.src = imgURL + imgName2;
}



// 이미지 테그에 focus 없애기
function autoBlur(){
	if(event.srcElement.tagName=="A"||event.srcElement.tagName=="IMG"){
		document.body.focus();
	}
}

//document.onfocusin = autoBlur;


function onSubMenuView(pIndex)
{
	var oMenu = sub_menu.childNodes;
	for(var i=0; i<oMenu.length; i++)
	{
		if(oMenu[i].tagName == "DD")
			oMenu[i].style.display = 'none';
	}

	var objMenu = eval("menu" + pIndex);
	if(objMenu.length)
	{
		for(var i=0; i<objMenu.length; i++)
		{
			objMenu[i].style.display = '';
		}
	}
	else
	{
		objMenu.style.display = '';
	}
}

function CheckLenNumber(pTextarea, pMaxLength, pMsg){
	var textValue = pTextarea.value;
	var textByte = textValue.bytes();
	count.innerHTML = textByte + ' / ' + pMaxLength + ' Byte';


    if (textByte> pMaxLength){
		alert(pMsg + "는 " + pMaxLength + "자까지만 쓰실 수 있습니다.");
		pTextarea.value = pTextarea.value.cut(pMaxLength);
		count.innerHTML = pTextarea.value.bytes() + '/' + pMaxLength;
		return;
    }

}

function docWrite(html) {
	document.write(html);
}


///////////////////////////////////////////////////////////////////////////
// 업로드 이미지 미리보기
///////////////////////////////////////////////////////////////////////////
function fnFileUploadPreview(thisObj, preViewer, imgID) {
    if (!/(\.gif|\.jpg|\.jpeg|\.png\.GIF|\.JPG|\.JPEG|\.PNG)$/i.test(thisObj.value)) {
        alert("이미지 형식의 파일을 선택하십시오");
        return false;
    }
    var viewID = preViewer;
    preViewer = (typeof (viewID) == "object") ? viewID : document.getElementById(viewID);
    var ua = window.navigator.userAgent;
    if (ua.indexOf("MSIE") > -1) {
        var img_path = "";
        if (thisObj.value.indexOf("\\fakepath\\") < 0) {
            img_path = thisObj.value;
        } else {
            thisObj.select();
            var selectionRange = document.selection.createRange();
            img_path = selectionRange.text.toString();
            thisObj.blur();
        }

        preViewer.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='fi" + "le://" + img_path + "', sizingMethod='scale')";
		preViewer.style.width = 83;
		preViewer.style.height = 113;
    } else {
        preViewer.innerHTML = "";
        var W = preViewer.offsetWidth;
        var H = preViewer.offsetHeight;
        var tmpImage = document.createElement("img");
        preViewer.appendChild(tmpImage);
        tmpImage.onerror = function() {
            return preViewer.innerHTML = "";
        }

        tmpImage.onload = function() {
            if (this.width > W) {
                this.height = this.height / (this.width / W);
                this.width = W;
            }
            if (this.height > H) {
                this.width = this.width / (this.height / H);
                this.height = H;
            }
        }
        if (ua.indexOf("Firefox/3") > -1) {
            var picData = thisObj.files.item(0).getAsDataURL();
            tmpImage.src = picData;
        } else {
            tmpImage.src = "file://" + thisObj.value;
        }
    }
    $('#' + imgID).hide();
}

///////////////////////////////////////////////////////////////////////////
// 인쇄
// fnPrint(pType, pFrame)
//  pType : 바로인쇄-print, 미리보기-preview, iframe 내용 출력-frame
//  pFrame : iframe 내용 출력인 경우 iframe 이름 아닌 경우는 공백('')
///////////////////////////////////////////////////////////////////////////
function fnPrint(pType, pFrame) {

    if (!factory.object) {
        alert("MeadCo's ScriptX ActiveX 컨트롤이 정상적으로 설치되지 않았습니다!\n\n본 페이지에서 제공하는 MeadCo's ScriptX 를 설치한 후 인쇄해 주세요.");
        return;
    } else {

        // 인쇄설정
        factory.printing.header = ""; // Header에 들어갈 문장 
        factory.printing.footer = ""; // Footer에 들어갈 문장
        factory.printing.portrait = true;  // true 면 세로 인쇄, false 면 가로 인쇄
        factory.printing.leftMargin = 2.0;  // 왼쪽 여백 사이즈
        factory.printing.topMargin = 2.0;  // 위 여백 사이즈
        factory.printing.rightMargin = 2.0;  // 오른쪽 여백 사이즈
        factory.printing.bottomMargin = 2.0;  // 아래 여백 사이즈

        //  factory.printing.SetMarginMeasure(2); // 테두리 여백 사이즈 단위를 인치로 설정합니다. 
        //  factory.printing.printer = "HP DeskJet 870C"; // 프린트 할 프린터 이름 
        //  factory.printing.paperSize = "A4"; // 용지 사이즈 
        //  factory.printing.paperSource = "Manual feed"; // 종이 Feed 방식 
        //  factory.printing.collate = true; // 순서대로 출력하기 
        //  factory.printing.copies = 2; // 인쇄할 매수 
        //  factory.printing.SetPageRange(false, 1, 3); // True로 설정하고 1, 3이면 1페이지에서 3페이지까지 출력

        if (pType == 'print') {
            factory.printing.Print(true); // 출력하기
        } else if (pType == 'preview') {
            factory.printing.Preview(); // 미리보기
        } else if (pType == 'frame') {
            factory.printing.Print(true, pFrame); // iframe 출력
            //<iframe name="프레임이름" width="0" height="0" frameborder="0" src="페이지주소"></iframe>
        }

    }

    self.close();
}



