
// NOTICE : 이 파일은 UTF-8 로 인코딩되어야 합니다.

// TODO : 이곳에 모든 페이지 공통으로 사용되는 자바스크립트를 정의하십시오.

var KR = 82;
var EN = 1;
var g_hWnd = null;

function getPostposition(k, idx)
{
	var rowIdx = gPostpostionLabel[k.toString().toUpperCase()];
	return gPostpositionTable[rowIdx][idx];
}

function getRoleName(s)
{
	switch (s.toLowerCase())
	{
		case 'student':
			return gStudentCaption;
			break;
		case 'teacher':
			return gTeacherCaption;
			break;
		case 'administrator':
			return gAdministratorCaption;
			break;	
	}
}

function PageMove(pageFormName, pageNo)
{
	var oForm = document.forms["pageForm"];
	if (oForm)
	{
		oForm[pageFormName].value = pageNo;
	}
	else
	{
		alert("페이지 정보를 담을 폼이 없습니다.\n\n페이지 이동을 할 수 없습니다.");
	}
	oForm.submit();
}

/*
	MP3 스트리머
*/
function Mp3StreamerBase()
{
	this.flashObjName = "mp3streamer";
	this.eventControlFunc = null;
	this.prevEventControlFunc = null;
}

Mp3StreamerBase.prototype = {
	setObj:function(flashObjName)
	{
		this.flashObjName = flashObjName;

		if (gURL_root == undefined)
			var gURL_root = '';

		showFlash(this.flashObjName, 1, 1, gURL_root + "/themes/_common/media/mp3streamer.swf", "", "position:absolute;top:-1000;left:-1000");
	},
	setEventController:function(eventControlFunc)
	{
		if (typeof(eventControlFunc) == "undefined")
		{
			alert("Not found '" + eventControlFunc + "' function.");
			return ;
		}

		this.prevEventControlFunc = this.eventControlFunc;
		this.eventControlFunc = eventControlFunc;

		g(this.flashObjName).attachEvent("FSCommand",this.eventControlFunc);
	},
	rollbackEventController:function()
	{
		this.eventControlFunc = this.prevEventControlFunc;
		this.prevEventControlFunc = null;
	},
	stopSound:function()
	{
		if (g(this.flashObjName) == null)
		{
			alert("Not found '" + this.flashObjName + "' object.");
			return ;
		}

		g(this.flashObjName).setVariable("execFunction", "StopSound");
	},
	playSound:function(soundPath, eventControlFuncName)
	{
		if (g(this.flashObjName) == null)
		{
			alert("Not found '" + this.flashObjName + "' object.");
			return ;
		}

		g(this.flashObjName).SetVariable("SoundUrl", soundPath);
		g(this.flashObjName).SetVariable("execFunction", "PlaySound");
	}
};

var gMp3Streamer = new Mp3StreamerBase();

function createMp3Streamer()	{ gMp3Streamer.setObj("mp3streamer"); }
function stopSound()			{ gMp3Streamer.stopSound(); }
function playSound(soundPath)	{ gMp3Streamer.playSound(soundPath); }
function mp3EventSet(fn)		{ gMp3Streamer.setEventController(fn); }
function mp3EventRollback()		{ gMp3Streamer.rollbackEventController(); }

/*
	TTS Play Sound
*/
function TTSPlaySound()
{
	this.mp3Streamer = null;

	this.init();
}

TTSPlaySound.prototype.init = function()
{
	this.mp3Streamer = new Mp3StreamerBase();
	this.mp3Streamer.setObj("TTS_mp3streamer");
};

TTSPlaySound.prototype.play = function(lang, text, pitch, speed, volume)
{
	if (lang == undefined)		var lang = 'en';
	if (text == undefined)		var text = '';
	if (pitch == undefined)		var pitch = '-1';
	if (speed == undefined)		var speed = '-1';
	if (volume == undefined)	var volume = '200';

	var soundPath = gURL_root + "/VWTTSServiceProxy.php?lang=" + lang + "&text=" + escape(text) + "&pitch=" + pitch + "&speed=" + speed + "&volume=" + volume;

	this.mp3Streamer.playSound(soundPath);
};

TTSPlaySound.prototype.playEn = function(text, pitch, speed, volume)
{
	this.play('en', text, pitch, speed, volume);
};

TTSPlaySound.prototype.playCn = function(text, pitch, speed, volume)
{
	this.play('cn', escape(text), pitch, speed, volume);
};

TTSPlaySound.prototype.playKo = function(text, pitch, speed, volume)
{
	this.play('ko', text, pitch, speed, volume);
};

TTSPlaySound.prototype.stop = function()
{
	this.mp3Streamer.stopSound();
};

/*
	필드별로 오름/내림차순 정렬 시켜줄 때 사용할 녀석 2.0
*/
function SortWizardBase() { };
SortWizardBase.prototype = {
	_form:null,
	_varName:'SortWizard',
	_sortFieldName:'sortField',
	_sortDirectionName:'sortDirection',
	_sortField:'',
	_sortDirection:'desc',
	_prefix:'__txtSortWizard_',
	_bInit:false,
	_bSetForm:false,
	InitVar:function(varName, sortFieldName, sortDirectionName)
	{
		if (varName != undefined)
		{
			this._varName = varName;
			this._prefix = '__txt' + varName + '_';
		}

		this._sortFieldName = sortFieldName;
		this._sortDirectionName = sortDirectionName;
	},
	Init:function(field, direction)
	{		
		this._sortField = field;
		this._sortDirection = direction;
		this._bInit = true;
	},
	Print:function(outputStr, sendValue)
	{
		document.write('<a href="javascript:' + this._varName + '.Sort(\'' + sendValue + '\');">' + outputStr);
		document.write('<span id="' + this._prefix + sendValue + '">');

		if (this._sortField == sendValue)
		{
			document.write(this.GetDirectionIcon(this._sortDirection));
		}

		document.write('</span>');
		document.write('</a>');
	},
	Sort:function(sendValue)
	{
		if (this._form)
		{
			if (this._form[this._sortFieldName] == undefined)
			{
				this.MakeForm(this._sortFieldName);
			}

			if (this._form[this._sortDirectionName] == undefined)
			{
				this.MakeForm(this._sortDirectionName);
			}

			this._form[this._sortFieldName].value = sendValue;
			this._form[this._sortDirectionName].value = this._sortDirection == 'desc' ? 'asc' : 'desc';
		}
		else
		{
			alert("필드 정렬 정보를 담을 폼이 없습니다.\n\n정렬 요청을 수행 할 수 없습니다.\n\nSetForm 메서드를 호출했는지 확인하십시오!");
			return ;
		}
		this._form.submit();
	},
	SetForm:function(formName)
	{
		if (this._bSetForm)
			return ;

		this._bSetForm = true;

		if (formName == undefined)
			formName = "pageForm";

		this._form = document.forms[formName];
	},
	MakeForm:function(inputName)
	{
		oInputSort = document.createElement("<input>");
		oInputSort.type = "hidden";
		oInputSort.name = inputName;
		oInputSort.id = inputName;
		oInputSort.value = "";
		this._form.appendChild(oInputSort);
	},
	GetDirectionIcon:function(direction)
	{
		if (direction == 'desc')
			return '▼';
		else
			return '▲';
	}
};

var SortWizard = new SortWizardBase;

/* 폼 생성 */
function AnonymForm(attributes)
{
	this.init(attributes);
}

AnonymForm.prototype = {
	_form:null,
	init:function(attributes)
	{
		var id = "__anonymForm_form:" + Math.random();

		oForm = document.createElement("form");
		oForm.id = id;

		var oBody = document.getElementsByTagName('body');
		oBody[0].appendChild(oForm);	

		this._form = g(id);

		for (var k in attributes)
		{
			this.setAttribute(k, attributes[k]);
		}
	},
	setAttribute:function(name, value)
	{
		this._form[name] = value;
	},
	setValue:function(name, value)
	{
		if (this._form[name] == undefined || this._form[name].value == undefined)
		{
			oInput = document.createElement("input");
			oInput.type = "hidden";
			oInput.id = "__anonymForm_input:" + name;
			oInput.name = name;
			oInput.value = value;
			this._form.appendChild(oInput);
		}
		else
		{
			this._form[name].value = value;
		}
	},
	submit:function()
	{
		this._form.submit();
	}
};

function showPopup(url, name, width, height, scrollbars, resizable, top, left)
{
	if (width == undefined)			width = 800;
	if (height == undefined)		height = 600;
	if (name == undefined)			name = "";

	if (scrollbars == undefined)	scrollbars = "yes";
	else if (scrollbars == true)	scrollbars = "yes";
	else if (scrollbars == false)	scrollbars = "no";

	if (resizable == undefined)		resizable = "yes";
	else if (resizable == true)		resizable = "yes";
	else if (resizable == false)	resizable = "no";

	if (top == undefined)	top = 0;
	if (left == undefined)	left = 0;

	// 열리는 팝업에서 height 값을 참조할 수 있게..
	if (url.indexOf("&__height") == -1)
		url += (url.indexOf('?') == -1 ? "?" : "&") + "__height=" + height;

	// 열리는 팝업에서 width 값을 참조할 수 있게..
	if (url.indexOf("&__width") == -1)
		url += (url.indexOf('?') == -1 ? "?" : "&") + "__width=" + width;

	if (width == "0" || height == "0")
	{
		hWnd = window.open(url, name, "fullscreen=1,scrollbars=" + scrollbars + ",resizable=" + resizable + ',top=' + top + ',left=' + left);
	}
	else
	{
		hWnd = window.open(url, name, "width=" + width + ",height=" + height + ",scrollbars=" + scrollbars + ",resizable=" + resizable + ',top=' + top + ',left=' + left);
	}
	
	hWnd.focus();

	return hWnd;
}

function resetForm(formName)
{
	document.forms[formName].reset();
}

function submitForm(formName, oFormField)
{
	if (this.isBubbling)
		return ;

	var oForm = document.forms[formName];

	if ((oForm.onsubmit && oForm.onsubmit()) || oForm.onsubmit == undefined)
	{
		if (oForm.page)
			oForm.page.value = "1";

		changeSubmitStatus('javascript:submitForm(', '처리 중..');

		if (this.isBubbling == undefined)
			this.isBubbling = true;

		if (oFormField != undefined)
		{
			for (var k in oFormField)
			{
				if (k == "" || typeof oFormField[k] == "function" || typeof oFormField[k] == "object" || typeof oFormField[k] == "array")
					continue;

				oForm[k].value = oFormField[k];
			}
		}

		oForm.submit();
	}
}

function changeSubmitStatus(strRef, strText)
{
	if (strRef == undefined)
		var strRef = "javascript:submitForm(";

	if (strText == undefined)
		var strText = "처리 중..";

	// 전송 전, submitForm 을 호출한 녀석을 disable 시킨다.
	var arrATags = document.getElementsByTagName("a");

	for (var i = 0; i < arrATags.length; i++)
	{
		var obj = arrATags[i];

		if (obj.href && obj.href.indexOf(strRef) == 0)
		{
			obj.removeAttribute('href');
			obj.style.textDecoration = "none";
			obj.style.color = "red";
			obj.blur();
			obj.innerHTML = '<span style="font-size:9pt;"><blink>' + strText + '</blink></span>';

			doBlink();
		}
	}
}

function doLogin()
{
	var oForm = document.forms['loginForm'];

	if (oForm.loginID.value == "")
	{
		alert("아이디를 입력하세요.");
		oForm.loginID.focus();
		return ;
	}

	if (oForm.passwd.value == "")
	{
		alert("비밀번호를 입력하세요.");
		oForm.passwd.focus();
		return ;
	}

	oForm.submit();
}

function doLogout(return_to)
{
	if (confirm("로그아웃하시겠습니까?") == false)
		return ;

	var url = gURL_root + gSitePath + "/auth.php?action=Logout";
	if (return_to != null)
		url += "&return_to=" + return_to;

	location.href = url;
}

// 일반형 학습 창 열기
function showLessonWindow(registered_curriculum_id, lesson_id, width, height, resizable, able_lesson)
{
	if (able_lesson != undefined && able_lesson == 0)
	{
		alert("선택하신 강의는 학습하실 수 없습니다.\n\n해당 강의는 학습 기록 조회만 가능합니다.");
		return ;
	}

	// 관리도구에서 호출 함
	if (arguments.length == 4)
	{
		able_lesson = resizable;
		resizable = height;
		height = width;
		width = lesson_id;
		lesson_id =  registered_curriculum_id;
		registered_curriculum_id = "";
	}
		
	showPopup(gURL_root + gSitePath + "/lecture/viewer.php?curriculum_type=normal&registered_curriculum_id=" + registered_curriculum_id + "&lesson_id=" + lesson_id, "lectureWnd", width, height, false, resizable);
}

// 스케줄형 학습 창 열기
function showScheduleLessonWindow(registered_curriculum_id, curriculum_schedule_id, width, height, resizable, able_lesson)
{
	if (able_lesson != undefined && able_lesson == 0)
	{
		alert("선택하신 강의는 학습하실 수 없습니다.\n\n해당 강의는 학습 기록 조회만 가능합니다.");
		return ;
	}

	showPopup(gURL_root + gSitePath + "/lecture/viewer.php?curriculum_type=schedule&registered_curriculum_id=" + registered_curriculum_id + "&curriculum_schedule_id=" + curriculum_schedule_id, "lectureWnd", width, height, false, resizable);
}

// 시퀀스형 학습 창 열기
function showSequenceLessonWindow(registered_curriculum_id, curriculum_sequence_id, width, height, resizable, able_lesson)
{
	if (able_lesson != undefined && able_lesson == 0)
	{
		alert("선택하신 강의는 학습하실 수 없습니다.\n\n해당 강의는 학습 기록 조회만 가능합니다.");
		return ;
	}

	showPopup(gURL_root + gSitePath + "/lecture/viewer.php?curriculum_type=sequence&registered_curriculum_id=" + registered_curriculum_id + "&curriculum_sequence_id=" + curriculum_sequence_id, "lectureWnd", width, height, false, resizable);
}

function showLessonObjectWindow(lesson_object_id, width, height, resizable, able_lesson)
{
	if (able_lesson != undefined && able_lesson == 0)
	{
		alert("선택하신 학습객체는 학습하실 수 없습니다.\n\n해당 학습객체는 학습 기록 조회만 가능합니다.");
		return ;
	}

	showPopup(gURL_root + gSitePath + "/lecture/viewer.php?lesson_object_id=" + lesson_object_id, "lectureWnd", width, height, false, resizable);
}

function showHomeworkWindow(homework_id, width, height, resizable, able_lesson)
{
	if (able_lesson != undefined && able_lesson == 0)
	{
		alert("선택하신 숙제는 학습하실 수 없습니다.\n\n해당 숙제는 학습 기록 조회만 가능합니다.");
		return ;
	}

	showPopup(gURL_root + gSitePath + "/lecture/homework-viewer.php?homework_id=" + homework_id, "homeworkWnd", width, height, false, resizable);
}

function showLessonLogByDate(date, user_id)
{
	// 학생용
	if (user_id == undefined)
		location.href = gAttendanceBookUrl + '?action=Inquiry&date=' + date;
	else // 학부모용
		location.href = gAttendanceBookUrl + '?action=Inquiry&date=' + date + "&user_id=" + user_id;
}


function showDailyLessonObjectLog(lesson_result_id, lesson_id, user_id, date)
{
	var url = gAttendanceBookUrl + "?action=ShowDailyLessonLog&lesson_id=" + lesson_id + 
				"&user_id=" + user_id + "&lesson_result_id=" + lesson_result_id + "&date=" + date;

	showPopup(url, "dailyLogWnd", 850, 600, true, false);
}

/* 우편번호 검색 결과에서 우편번호를 클릭 시 */
function selectionZipcode(zipcode_1, zipcode_2, address)
{
	var oZipFindForm = document.forms['zipfindForm'];

	var targetForm = oZipFindForm.formName.value;
	var targetZip1 = oZipFindForm.zipcode1.value;
	var targetZip2 = oZipFindForm.zipcode2.value;
	var targetAddr = oZipFindForm.address.value;
	var targetFocusFormName = oZipFindForm.focusFormName.value;

	var oForm = opener.document.forms[targetForm];

	oForm[targetZip1].value = zipcode_1;
	oForm[targetZip2].value = zipcode_2;
	oForm[targetAddr].value = address;

	if (oForm[targetFocusFormName])
		oForm[targetFocusFormName].focus();

	window.close();
}

function show_layer_pop(obj_name, nsEvent) 
{
	var theEvent = nsEvent ? nsEvent : window.event;

//	var newX = theEvent.clientX + document.documentElement.scrollLeft;
//	var newY = theEvent.clientY + document.documentElement.scrollTop;

//	if(obj_name == 'main_lecture')
//	{
	var newX = screen.width/2 - document.getElementsByTagName('div')['layer_'+obj_name].offsetWidth / 2;
	var newY = screen.height/2 - document.getElementsByTagName('div')['layer_'+obj_name].offsetHeight / 2 + document.documentElement.scrollTop;
//	}

	g('layer_'+obj_name).style.left = newX  + 'px';
	g('layer_'+obj_name).style.top = newY + 'px';

	new Draggable('layer_'+obj_name);
	g('layer_'+obj_name).style.display = 'inline';
}

function layerClose(obj_name) 
{
	g('layer_'+obj_name).style.display = 'none';
}

function show_main_lecture(today, user_id) 
{
	g('show_main_lecture_frm').src = gURL_root + gSitePath + '/front/pages.php/cyberclass?action=showlecture&date=' + today + '&user_id=' + user_id; 
	show_layer_pop('main_lecture', event);
}

function show_today_lecture(today, user_id, display_date) 
{
	g('layer_lecture').style.display = 'block';
	g('show_today_lecture_frm').src = gURL_root + gSitePath + '/front/pages.php/cyberclass?action=showlecture&date=' + today + '&user_id=' + user_id; 
	show_layer_pop('lecture', event);

	g('display_date').innerHTML = display_date;
}

function show_today_event(today) 
{
	g('layer_branch_event').style.display = 'block';
	g('show_today_event_frm').src = gURL_root + gSitePath + '/front/pages.php/cyberclass?action=showbranchevent&date=' + today   ; 
	show_layer_pop('branch_event', event);
}

function showCyberClass(user_id)
{
	var oForm = new AnonymForm({
		action:gSelf,
		method:"GET"
	});

	oForm.setValue('action', 'Default');
	oForm.setValue('user_id', user_id);

	oForm.submit();
}

function showCyberClassForTeacher(class_id)
{
	var oForm = new AnonymForm({
		action:gSelf,
		method:"GET"
	});

	oForm.setValue('action', 'Default');
	oForm.setValue('class_id', class_id);

	oForm.submit();
}

function showAttendanceBook(user_id)
{
	var oForm = new AnonymForm({
		action:gSelf,
		method:"GET"
	});

	oForm.setValue('action', 'Default');
	oForm.setValue('user_id', user_id); // 보관 후, 창 닫기

	oForm.submit();
}

function goLessonByIdentifier(identifier,width,height)
{
	if (isLogined == false)
	{
		alert("로그인 후, 이용 할 수 있습니다.");
		return ;
	}
	var url = gURL_root + gSitePath + "/lecture/goLesson.php?identifier=" + identifier;
	showPopup(url, "actypWnd", width || 1000, height || 700, false, false);
}

function goMenuByIdentifier(identifier)
{
	var url = gURL_root + gSitePath + "/front.php?action=GoMenu&identifier=" + identifier;
	location.href = url;
}

function goProgramMain(module_name)
{
	var url = gURL_root + gSitePath + "/lecture/goProgramMain.php?module_name=" + module_name;

	if (window.parent)
		window.parent.location.href = url;
	else
		window.location.href = url;
	
}

/* 확장형 테이블 컨트롤 */
function ExtendTable(elementID, instanceName, oOptions)
{
	this._elementID = elementID || '__list';
	this._instanceName = instanceName || '__extList';

	if (oOptions == undefined)
		var oOptions = {};

	this.init(oOptions);
}

ExtendTable.prototype.init = function(oOptions)
{
	var oList = document.getElementById(this._elementID);

	oList.style.cssText += ";border-right:none !important;border-left:none !important";

	for (var i = 0; i < oList.rows.length ; i++ )
	{
		for (var j = 0; j < oList.rows[i].cells.length ; j++ )
		{
			oList.rows[i].cells[j].style.cssText += ";border-right:none !important;border-left:none !important";

			if (oOptions.useDetailRow)
			{
				if (i > 0 && i%2)
				{
					var oLink = oList.rows[i].cells[j].getElementsByTagName('a');

					if (oLink.length)
					{
						oLink[0].orgHref = oLink[0].href;
						oLink[0].href = 'javascript:' + this._instanceName + '.showDetail(' + Math.floor(i/2) + ');';
					}
				}
			}
		}
	}
};

ExtendTable.prototype.showDetail = function(rowIdx)
{
	var nRealRowIdx = (rowIdx+1) * 2;
	var oList = document.getElementById(this._elementID);

	oList.rows[nRealRowIdx].style.display = "";

	for (var i = 0; i < oList.rows[nRealRowIdx - 1].cells.length ; i++ )
	{
		oList.rows[nRealRowIdx - 1].cells[i].orgCssText = oList.rows[nRealRowIdx - 1].cells[i].style.cssText;
		oList.rows[nRealRowIdx - 1].cells[i].style.cssText += ';border-bottom:none !important;';
	}

	var oLink = oList.rows[nRealRowIdx - 1].cells[i - 1].getElementsByTagName('a');
	oLink[0].href = 'javascript:' + this._instanceName + '.hideDetail(' + rowIdx + ');';

	var oImg = oList.rows[nRealRowIdx - 1].cells[i - 1].getElementsByTagName('img');
	oImg[0].src = oImg[0].src.toString().replace(/btn_page_down/, 'btn_page_up');

	oList.rows[nRealRowIdx].cells[0].orgCssText = oList.rows[nRealRowIdx].cells[0].style.cssText;
	oList.rows[nRealRowIdx].cells[0].style.cssText += ';border-top:none !important;';


	// 확장 전에 데이터 불러오는 중... 표시
	oList.rows[nRealRowIdx].cells[0].innerHTML = '<div style="color:red;text-align:center;width:100%;"><BLINK>데이터 불러오는 중...</BLINK></div>';
	doBlink();

	// 선택된 것의 상세 정보를 획득합니다.
	var oLink = oList.rows[nRealRowIdx - 1].cells[oList.rows[nRealRowIdx - 1].cells.length - 1].getElementsByTagName('a');
	var inquiryUrl = oLink[0].orgHref;

	oXml = sendXmlHttpRequest(inquiryUrl, {}, this.onLoaded, {_this:this,rowIdx:rowIdx});
};

ExtendTable.prototype.hideDetail = function(rowIdx)
{
	var nRealRowIdx = (rowIdx+1) * 2;
	var oList = document.getElementById(this._elementID);

	oList.rows[nRealRowIdx].style.display = "none";

	for (var i = 0; i < oList.rows[nRealRowIdx - 1].cells.length ; i++ )
	{
		oList.rows[nRealRowIdx - 1].cells[i].style.cssText = oList.rows[nRealRowIdx - 1].cells[i].orgCssText;
	}

	var oLink = oList.rows[nRealRowIdx - 1].cells[i - 1].getElementsByTagName('a');
	oLink[0].href = 'javascript:' + this._instanceName + '.showDetail(' + rowIdx + ');';

	var oImg = oList.rows[nRealRowIdx - 1].cells[i - 1].getElementsByTagName('img');
	oImg[0].src = oImg[0].src.toString().replace(/btn_page_up/, 'btn_page_down');

	oList.rows[nRealRowIdx].cells[0].style.cssText = oList.rows[nRealRowIdx].cells[0].orgCssText;
};

ExtendTable.prototype.onLoaded = function(oXml, oArg)
{
	doBlink(false);

	var nRealRowIdx = (oArg.rowIdx+1) * 2;
	var oList = document.getElementById(oArg._this._elementID);

	oList.rows[nRealRowIdx].cells[0].innerHTML = oXml.responseText;
};
