/* utf-8 인코딩 */
function checkDuplicateBBSId(formName, inputName)
{
	var oForm = document.forms[formName];
	var oID = oForm[inputName];

	if (oForm.branch_id.tagName.toLowerCase() == "select")
		var branch_id = selectedValue(g('branch_id'));
	else
		var branch_id = oForm.branch_id.value;

	if (branch_id == null || branch_id == "" )
	{
		alert("게시판을 생성할 학원을 선택하세요.");
		return ;
	}

	if (oID.value.trim() == "")
	{
		alert("중복 검사할 게시판 ID를 입력하세요.");
		oID.focus();
		return ;
	}

	if (!/^[a-zA-Z0-9]+$/.test(oID.value))
	{
		alert("게시판 ID는 영어(대/소문자 구별 없음), 숫자를 사용해서 만드셔야 합니다.");
		oID.focus();
		return ;
	}

	var oXml = sendXmlHttpRequest(getModuleUrl('service.bbs.all'), {
			action:'IDCheck',
			branch_id: branch_id,
			bbsID: oID.value
		});

	alert(oXml.responseXml.selectSingleNode('//message/text()').nodeValue);

	return ;
}

function checkDuplicateBBSCategoryName(bbsID, formName, inputName)
{
	var oForm = document.forms[formName];
	var oID = oForm[inputName];

	if (g('branch_id').tagName.toLowerCase() == "select")
		var branch_id = selectedValue(g('branch_id'));
	else
		var branch_id = g('branch_id').value;

	if (branch_id == null || branch_id == "")
	{
		alert("게시판 분류를 생성할 학원을 선택하세요.");
		return ;
	}

	if (oID.value.trim() == "")
	{
		alert("중복 검사할 게시물 분류 명을 입력하세요.");
		oID.focus();
		return ;
	}

	var oXml = sendXmlHttpRequest(getModuleUrl('service.bbs.all'), {
			action:'CategoryCheck',
			branch_id: branch_id,
			bbsID: bbsID,
			category_name: oID.value
		});

	alert(oXml.responseXML.selectSingleNode('//message/text()').nodeValue);

	return ;
}

function showBBS(branch_id, bbsID)
{
	showPopup(getModuleUrl('service.bbs.viewer') + "?action=List&branch_id=" + branch_id + "&id=" + bbsID + "&__height=650", bbsID + "Wnd", 850, 650, true, true);
}

function doDeleteBBS(bbs_id)
{
	if (confirm("게시판을 삭제하시겠습니까?") == false)
		return ;

	var oForm = new AnonymForm({
		action:gSelf,
		method:"POST"
	});

	oForm.setValue('action', 'DoDeleteBBS');
	oForm.setValue('bbs_id', bbs_id);
	oForm.setValue('returnURL', gSelf);
	oForm.submit();
}

function doDeleteBBSCategory(bbs_category_id)
{
	if (confirm("선택된 분류를 삭제하시겠습니까?\n\n해당 분류로 설정된 게시물은 모두 미분류 상태로 변경됩니다.") == false)
		return ;

	var oForm = new AnonymForm({
		action:gSelf,
		method:"POST"
	});

	oForm.setValue('action', 'DoDeleteBBSCategory');
	oForm.setValue('bbs_category_id', bbs_category_id);
	oForm.setValue('returnURL', gSelf + '?' + gQueryString);
	oForm.submit();
}

function doDeleteTopic(branch_id, bbsID, topic_id)
{
	if (isLogined == false)
	{
		location.href = gSelf + '?action=TopicDeleteConfirm&branch_id=' + branch_id + '&id=' + bbsID + '&topic_id=' + topic_id;
		return ;
	}

	if (confirm("선택하신 게시물을 삭제하시겠습니까?\n\n답변 글이 있는 경우, 함께 삭제됩니다.") == false)
		return ;

	location.href = gSelf + '?action=TopicDelete&branch_id=' + branch_id + '&id=' + bbsID + '&topic_id=' + topic_id;
}

function resizeContentHolder()
{
	var sAgent=navigator.userAgent.toLowerCase();

	if (sAgent.indexOf("msie")!=-1)
	{
		var objBody = window.frames["contentHolder"].document.body;
		var objFrame = document.all["contentHolder"];

		objFrame.style.height = objBody.scrollHeight + (objBody.offsetHeight - objBody.clientHeight) + 50;
	}
	else
	{
		var objBody = document.getElementById("contentHolder").contentDocument.body;
		var objFrame = window.document.getElementById("contentHolder");

		objFrame.style.height = objBody.scrollHeight + (objBody.offsetHeight - objBody.clientHeight) + 50 + 'px';
	}
}

function doVote()
{
	var oForm = document.forms['viewForm'];

	var item = getRadioValue(oForm.poll_item);

	if (item == "")
	{
		alert("항목을 선택 후, 투표 버튼을 눌러 주세요.");
		return ;
	}

	ajax.action(gSelf);
	ajax.clearValue();
	ajax.setValueFromObject({
		action:'DoVote',
		branch_id:getFormValue(oForm.branch_id),
		id:oForm.id.value,
		topic_id:oForm.topic_id.value,
		poll_item_id:item
	}); // form 값

	ajax.call("poll"); // 결과 처리 후, 화면 갱신이 이뤄질 AJAX ID
}

function showPollResult()
{
	var oForm = document.forms['viewForm'];

	ajax.action(gSelf);
	ajax.clearValue();
	ajax.setValueFromObject({
		action:'ShowPollResult',
		branch_id:getFormValue(oForm.branch_id),
		id:oForm.id.value,
		topic_id:oForm.topic_id.value
	}); // form 값

	ajax.call("poll"); // 결과 처리 후, 화면 갱신이 이뤄질 AJAX ID
}

function replySubmit()
{
	var oViewForm = document.forms['viewForm'];

	if (isLogined == false)
	{
		if (oViewForm.reply_author.value.toString().trim() == "")
		{
			alert("덧글 작성자 이름을 입력하세요.");
			oViewForm.reply_author.focus();
			return ;
		}

		if (oViewForm.reply_passwd.value.toString().trim() == "")
		{
			alert("덧글 삭제 시, 사용할 패스워드를 입력하세요.");
			oViewForm.reply_passwd.focus();
			return ;
		}
	}

	if (oViewForm.reply_content.value.toString().trim() == "")
	{
		alert("덧글 내용을 입력하세요.");
		oViewForm.reply_content.focus();
		return ;
	}

	var oForm = new AnonymForm({
		action:gSelf,
		method:"POST"
	});

	oForm.setValue('action', 'DoAddReply');

	if (oViewForm.branch_id)
		oForm.setValue('branch_id', oViewForm.branch_id.value);

	oForm.setValue('id', oViewForm.id.value);
	oForm.setValue('topic_id', oViewForm.topic_id.value);
	if (isLogined == false)
	{
		oForm.setValue('author', oViewForm.reply_author.value);
		oForm.setValue('passwd', oViewForm.reply_passwd.value);
	}
	oForm.setValue('content', oViewForm.reply_content.value);
	oForm.setValue('returnURL', gSelf + '?' + gQueryString);
	oForm.submit();
}

function doDeleteReply(reply_id, writerRole)
{
	var oViewForm = document.forms['viewForm'];

	var branch_id = oViewForm.branch_id.value;
	var id = oViewForm.id.value;
	var topic_id = oViewForm.topic_id.value;
	var returnURL = gSelf + '?' + gQueryString;

	if (writerRole == "guest")
	{
		location.href = gSelf + '?action=DeleteReply&branch_id=' + branch_id + '&id=' + id + '&topic_id=' + topic_id + '&reply_id=' + reply_id + '&returnURL=' + escape(returnURL);
		return ;
	}

	if (confirm("선택하신 덧글을 삭제하시겠습니까?") == false)
		return ;

	var oForm = new AnonymForm({
		action:gSelf,
		method:"POST"
	});

	oForm.setValue('action', 'DoDeleteReply');

	if (oViewForm.branch_id)
		oForm.setValue('branch_id', branch_id);

	oForm.setValue('id', id);
	oForm.setValue('topic_id', topic_id);
	oForm.setValue('reply_id', reply_id);
	oForm.setValue('returnURL', returnURL);
	oForm.submit();
}

// 음성녹음 엔진
function voiceRecordEngine(o)
{
	this.claName = o.claName;
	this.objName = o.axName;
	this.postUrl = o.postUrl;

	this.startBtnId = o.startBtnId;
	this.startBtnClickedId = o.startBtnClickedId;
	this.stopBtnId = o.stopBtnId;
	this.volumeBarId = o.volumeBarId;
	this.volumeMaxWidth = o.volumeMaxWidth;

	if (o.startAndStopToggle == undefined)
		this.startAndStopToggle = true;
	else
		this.startAndStopToggle = o.startAndStopToggle;

	this.maxTimeOut = o.maxTimeOut || 5;
	this.maxTimeOut = this.maxTimeOut * 60 * 1000;

	this.mp3Path = '';

	this.tempMp3FileName = o.tempMp3FileName || 'test';
	this.tempMp3FileNameAuto = o.tempMp3FileNameAuto || false;
	
	this.stopViaButton = false;

	this.onRecordStop = o.onRecordStop;

	this.writeObject();
}

voiceRecordEngine.prototype = {
	writeObject:function()
	{
		document.writeln('<object classid="CLSID:A1C97782-FB09-402F-9C02-3621AA92A0EE" id="' + this.objName + '" style="width:1px;height:1px;position:absolute;top:-1000px;left:-1000px;"></object>');

		if (!g('AxRecog'))
		{
			document.writeln('<object style="position:absolute;bottom:0px;right:0px;" id="AxRecog" classid="clsid:7FAC66A6-39B2-430E-BAF6-ED194D0BF5EC" width="1" height="1"></object>');
		}

		document.writeln('<script for="' + this.objName + '" event="OnStopRecord(path, bEpd)">');
		document.writeln(this.claName + '.setFilePath(path);');
		document.writeln('</script>');

		document.writeln('<script for="' + this.objName + '" event="OnVolumeChanged(fVal)">');
		document.writeln(this.claName + '.onVolumeChanged(fVal);');
		document.writeln('</script>');

//		document.writeln('<script for="' + this.objName + '" event="OnErrorRecord(code)">');
//		document.writeln('</script>');

		if (this.startAndStopToggle)
		{
			document.getElementById(this.startBtnId).style.display = 'inline';
			document.getElementById(this.stopBtnId).style.display = 'none';
		}
		else
		{
			document.getElementById(this.startBtnId).style.display = 'inline';
			document.getElementById(this.startBtnClickedId).style.display = 'none';			
		}
	},
	start:function()
	{
		try
		{
			// 임시폴더 경로 획득을 위해 인식엔진에 있는 GetTempDir() 메서드 체크
			var tempDir = g('AxRecog').GetTempDir(); // 만약 설치안되있다면 오류 날꺼임

			var obj = document.getElementById(this.objName);

			obj.SetMaxTimeOut(this.maxTimeOut); // 기본 5분간 녹음
			obj.SetVolume(true); // 볼륨 이벤트 받음

			if (this.tempMp3FileNameAuto)
				this.tempMp3FileName = 'V' + Math.random().toString().replace(/\./g,'');

			obj.StartRecord(this.tempMp3FileName, false);
		}
		catch (e)
		{
			alert('음성 녹음 엔진이 설치되어 있지 않습니다.');
			return ;
		}

		if (this.startAndStopToggle)
		{
			document.getElementById(this.startBtnId).style.display = 'none';
			document.getElementById(this.stopBtnId).style.display = 'inline';
		}
		else
		{
			document.getElementById(this.startBtnId).style.display = 'none';
			document.getElementById(this.startBtnClickedId).style.display = 'inline';
		}

		this.stopViaButton = false;
	},
	stop:function()
	{
		try
		{
			this.stopViaButton = true;

			document.getElementById(this.objName).StopRecord();	
		}
		catch (e)
		{
			alert('음성 녹음 엔진이 설치되어 있지 않습니다.');
			return ;
		}

		if (this.startAndStopToggle)
		{
			document.getElementById(this.startBtnId).style.display = 'inline';
			document.getElementById(this.stopBtnId).style.display = 'none';
		}
		else
		{
			document.getElementById(this.startBtnId).style.display = 'inline';
			document.getElementById(this.startBtnClickedId).style.display = 'none';
		}

		try
		{
			var tempDir = g('AxRecog').GetTempDir();
		}
		catch (ex)
		{
			return ;
		}

		var mp3Path = tempDir + this.tempMp3FileName + ".mp3";

		if (typeof this.onRecordStop == "function")
		{
			this.onRecordStop(mp3Path);
		}
	},
	postMp3:function(path)
	{
		if (path != undefined)
		{
			var arrPath = path.split("\\");
			path = arrPath[arrPath.length - 1].substr(0,arrPath[arrPath.length - 1].length - 4);
		}

		var res = document.getElementById(this.objName).PostMp3(this.postUrl, path || this.tempMp3FileName);

		return res;
	},
	setFilePath:function(path)
	{	
		if (this.startAndStopToggle)
		{
			document.getElementById(this.startBtnId).style.display = 'inline';
			document.getElementById(this.stopBtnId).style.display = 'none';
		}
		else
		{
			document.getElementById(this.startBtnId).style.display = 'inline';
			document.getElementById(this.startBtnClickedId).style.display = 'none';
		}

		this.mp3Path = path;

		if (!this.stopViaButton)
		{
			alert((this.maxTimeOut/60)+'분간의 녹음이 끝났습니다.');
		}
	},
	getFilePath:function()
	{
		return this.mp3Path;
	},
	onVolumeChanged:function(fVal)
	{
		document.getElementById(this.volumeBarId).style.width = parseInt(this.volumeMaxWidth) - Math.floor(fVal * parseInt(this.volumeMaxWidth) / 100);
	}
};

// mp3 사운드 재생
var gPrevSoundFileId = null;

function bbsSoundPlay(file_id, file_url)
{
	if (gPrevSoundFileId != null)
	{
		show(g('__playSound_' + gPrevSoundFileId));
		hide(g('__stopSound_' + gPrevSoundFileId));
	}

	hide(g('__playSound_' + file_id));
	show(g('__stopSound_' + file_id));

	playSound(file_url);

	gPrevSoundFileId = file_id;
}

function bbsSoundStop()
{
	if (gPrevSoundFileId != null)
	{
		show(g('__playSound_' + gPrevSoundFileId));
		hide(g('__stopSound_' + gPrevSoundFileId));
	}

	stopSound();

	gPrevSoundFileId = null;
}

