//go url
function goUrl(url){
	window.location.href=url;
}

function goMylb(userId, option){
	if(typeof userId == 'undefined' || userId == '')
		return;
		
	var winName = "mylb_who";
	if(option == 1)
		winName = 'mylb_me';	
	
	openDenyPopup('/mylb/who?userId='+userId, '978', '600', 'no', winName, 'yes', 'no');
}

function goMylbByParam(param){
	openDenyPopup('/mylb/who?'+param, '978', '600', 'no', 'mylb_who', 'yes', 'no');
}

function getLayerList(page, command, divId) {
	if (null == page) page = 1;
		
	var listLayer = document.getElementById(divId);	
	if (typeof listLayer == "undefined" || listLayer == null) {
		alert("[ERROR getLayerList] display layer(" + divId + ") not found.");
		return;
	}
	
	var parameters = '&page=' + page;
	
	new Ajax.Request(unescape(command), {
			method:'post',
			encoding: 'UTF-8',
			parameters: parameters,
			onSuccess: function(request) {	
				listLayer.innerHTML = request.responseText;
			},
			onFailure: function(request) {
				if(request.status == 401)
					GNBLogin();
				alert("오류가 발생하였습니다.");
			}
		}
	);
}

function goItem(itemId){
	openDenyPopup('/style/itemlist/itemview?itemId=' + itemId, 450, 580); 
}

// 도전 코디네이터 
function contestRecommend(eventId, contestId, itemId) {	
	//channel,hostname,uri_part defined in GNB_channel
	var command = 'recommendContest';

	if (channel == 1 || channel == 5) {
		var parameters = '&url='+escape(window.location)+'&eventId='+eventId+'&contestId='+contestId+'&command='+uri_part+command+'&itemId='+itemId;

		if (channel == 1)		//yahoo
			goUrl(web_login + "&return_url=" + escape( 'http://'+hostname+'/common/inc/loginCheck_yahoo?id=7' + parameters ));
		else if (channel == 5) 	// daum
			goUrl(web_login + "&return_url=" + escape( 'http://'+hostname+'/common/inc/loginCheck_daum?id=7' + parameters));
	} 
	else {						//plaync
		new Ajax.Request("/common/inc/loginCheck",
			{
				method:'get',
				encoding: 'UTF-8',
				onSuccess : function(request) {
					if(request.responseText != 'true') {
						//alert('e??e¸i?? e?¨e¸°i??e?¤eⓒ´ e¡?e·¸i?¸i?? i?´i￡¼i?¸i??.');
						goUrl(web_login + "&return_url=" + escape(window.location));
						return;
					} else {
						recommendContest(eventId, contestId, command, itemId);	
					}
				},
				onFailure: function() {
					alert("e¡?e·¸i?¸ i?￢e¶ i?¸i¶?i?? i?¤i?¨i??i?μe??e?¤. ");
				}
			}
		);
	}		
}
function recommendContest(eventId, contestId, command, itemId){
	var parameters = {};
	parameters.eventId = eventId;
	parameters.contestId = contestId;
	parameters.itemId = itemId;
	
	new Ajax.Request(unescape(command),
		{
			method:'post',
			encoding: 'UTF-8',
			parameters: parameters,
			onSuccess: function(request) {
				var result = eval(request.responseText);
				if ( result >= 1 ) {
					alert("이미 투표하셨습니다.");
				} else if ( result == 0 ) {
					alert("투표되었습니다.");
					if(channel != 1 && channel != 5){	
						getGMContest(eventId, contestId);
					}
				}
			}, 
			onFailure: function() {
				alert("서버와의 통신이 원활하지 않습니다.");
			}
		}
	);
}
function getGMContest(eventId, contestId) {
	var eventviewLayer = $("pnlEventview");	
	if ((typeof eventviewLayer == "undefined") || (null == eventviewLayer)) {
		alert("[ERROR getGMContest] eventview display layer not found.");
		return;
	}
	
	var command = "coordicontent";
	var parameters = "eventId=" + eventId + "&contestId=" + contestId;

	new Ajax.Updater({success: 'pnlEventview'}, command, {
			method:'post',
			encoding: 'UTF-8',
			parameters: parameters,
			evalScripts: true,
			onFailure: function() {
				alert("서버와의 통신이 원활하지 않습니다.");
			}
		}
	);
}



function loginCheckAndGoUrl(command){
	//channel,hostname,uri_part defined in GNB
	if(channel == 1 || channel == 5){	//yahoo,daum		
		goUrl(web_login + "&return_url="  + escape('http://'+hostname+uri_part+command) );
						
	} else {			//plaync
		if( isLogged() == 'true' ) {	
			goUrl(command);	
		} else {
			goUrl(web_login + "&return_url=" + escape(window.location));
		}
	}	

}

function goWriteArticleForm(category) {
	var command = 'writeForm';
	if(category > 0 ){
		command += "?category=" + category;
	}
	loginCheckAndGoUrl(command);
}

function goReWriteArticleForm(articleID) {
	var command = "reWriteForm?articleID=" + articleID;	
	loginCheckAndGoUrl(command);
}

function goModifyArticleForm(articleID) {
	var command = "modifyForm?articleID=" + articleID;
	loginCheckAndGoUrl(command);			
}

var req_music = null;
function checkLogin_musiclist(funcName, articleID) {
/*	req = null;
	req = getXMLHttpRequest();
	req.open("GET","/common/inc/loginCheck",true);
	req.onreadystatechange = eval(funcName);
	req.send(null);
*/ 

	var mode = 'comment';
	if( funcName == 'checkCommentReply' ) {
		mode = 'reply';
		funcName = 'checkComment_musiclist';
	} 
	
	new Ajax.Request(	"/common/inc/loginCheck", {	
					method:'get',
					encoding: 'UTF-8',
					onComplete: function(result) {
						req_music = result;
						var x = funcName + "(" + articleID + ", '" + mode + "')"; 	// checkComment Function call
						if(funcName == 'checkCommentLogin_musiclist') {
							x = funcName + '()'; // 
						}
						eval(x);
					},
					onFailure: function() {	alert("로그인여부 호출에 실패했습니다.");	}
											}
			);	// end of Ajax.Request()
}
			
var gCommentSubmitcount = 0;
function checkComment_musiclist(articleID, mode) {
	if (gCommentSubmitcount > 0)
		return false;
	
	var commentForm = null;
	if(mode == 'comment') {
		commentForm = 'WriteComment' + articleID;
	}
	else if(mode == 'reply') {
		commentForm = 'writeCommentReplyForm';
	}
	
	if(req_music.responseText != 'true') {
		alert('댓글을 남기시려면 로그인을 해주세요.');
		goUrl(web_login + "&return_url=" + escape(window.location));
		return;
	} else {
		if(commentCheck_musiclist(articleID, mode)){	
			if(mode == 'comment') {
				document.getElementById('WriteComment'+articleID).content.value = document.getElementById('content'+articleID).value;
			}
			else if(mode == 'reply') {
				document.getElementById('writeCommentReplyForm').articleID.value = articleID;
			}
			
			//channel,hostname,uri_part defined in GNB
			/*
			if(channel == 1){	//yahoo		
				var params = Form.serialize('WriteComment'+articleID);	
				alert(params);	
				goUrl(web_login + "&return_url="  + escape('http://'+hostname+'/board/musiclist/writeComment?'+params)) ;
		
			} else {			//plaync
			*/
				gCommentSubmitcount++;
				document.getElementById(commentForm).action = "/board/musiclist/writeComment";
				document.getElementById(commentForm).submit();						
			//}			
		}
		
	}	
}

function commentCheck_musiclist(articleID, mode){
	var content = null; 
	if(mode == 'reply') {
		content = $('contentReply');
	}
	else if (mode == 'comment') {
		content = $('content'+articleID);
	}
	// var content = document.getElementById('content'+articleID)

	if(content == null || content.value.trim() == '') {
		alert('댓글을 입력해 주세요.');
		content.focus();
		return false;
	}
	if(content.value.length > 1000) {
		alert('댓글은 300자까지만 가능합니다.');
		content.value = content.value.substring(0,300);
		content.focus();
		return false;
	}
	if(content.value.length < 2) {
		alert('댓글은 2자 이상 입력해야합니다.');
		content.focus();
		return false;
	}
	return true;
}

function checkCommentLogin_musiclist() {
	try {
		if(req_music.responseText != 'true') {
			//alert('댓글을 남기시려면 로그인을 해주세요.');
			goUrl(web_login + "&return_url=" + escape(window.location));
			return;
		}
	} catch(e) {
		if(req_music.readyState == 4 && req_music.status == 200) 
			alert('예기치 않은 오류가 발생했습니다.\n 메시지:'+e.message);
	}
}

function deleteComment_musiclist(articleID, idx, subIdx, queryString) {
	if(confirm('댓글을 삭제하시겠습니까?')) {
		var command = '/board/musiclist/deleteComment?articleID='+articleID+'&idx='+idx+'&subidx='+subIdx+'&queryString='+escape(queryString);
		
		//channel,hostname,uri_part defined in GNB
		if(channel == 1 || channel == 5){	//yahoo, daum		
			goUrl(web_login + "&return_url="  + escape('http://'+hostname+command) );
							
		} else {			//plaync
			if( isLogged() == 'true' ) {			
				goUrl(command);		
			} else {
				goUrl(web_login + "&return_url=" + escape(window.location));
			}
		}
	
	}
}

function checkContentSubmit() {	
	var selectedCategory = 0;

	for(var i=0;i<document.getElementById('category').length;i++){	
		if(i > 0 && document.getElementById('category')[i].selected == true){
			selectedCategory =  document.getElementById('category')[i].value;
		}
	}

	if(( selectedCategory == 3 || selectedCategory == 12 )	/* 3:포토, 12:스샷 */
			&& !isContainsIMG(EditContent()) ){
		alert("이미지를 등록해야 글쓰기가 완료됩니다.\n[이미지편집]이나, [그림그리기]버튼으로 이미지를 등록 할 수 있습니다.");	
		return false;
	} else if( selectedCategory == 11 	/* 11:동영상 */
			&& !isContainsMOVIE(EditContent()) ){
		alert("동영상을 등록해야 글쓰기가 완료됩니다.\n[멀티미디어걸기]버튼으로 동영상을 등록 할 수 있습니다.");	
		return false;
	} else {
		return true;
	}
}

function isContainsIMG(strValue)
{
	var regStr = "<IMG";
	var result = strValue.toUpperCase().indexOf(regStr);
	var boolResult = false;
	
	if(result < 0) 
		boolResult =  false;
	else 
		boolResult =  true;
	
	return boolResult;
}

function isContainsMOVIE(strValue)
{
	var regStr = "<EMBED";
	var result = strValue.toUpperCase().indexOf(regStr);
	var boolResult = false;
	
	if(result < 0) 
		boolResult =  false;
	else 
		boolResult =  true;
	
	return boolResult;
}
function goPage(page) {
	var frm = document.getElementById('articleListForm')
	
	var searchQueryString = frm.searchQueryString.value;
	var nCategory = frm.category.value;
	var searchBlock = frm.searchBlock.value;
	
	//var strUrl = location.pathname + '?page=' + page + '&searchBlock=' + searchBlock + searchQueryString;
	var strUrl = 'list?page=' + page + '&searchBlock=' + searchBlock + searchQueryString;
			
	if( nCategory.length > 0 && !isNaN(nCategory) )
		strUrl += "&category=" + nCategory;
	
	//view's innerlist

	if( typeof(frm.articleID) != 'undefined' ) {
		var articleID = frm.articleID.value;	
		if( articleID.length > 0 && !isNaN(articleID) )
			strUrl += "&articleID=" + articleID;
	}
	
	if( typeof(frm.commentPage) != 'undefined' ) {
		var commentPage = frm.commentPage.value;	
		if( commentPage.length > 0 && !isNaN(commentPage) )
			strUrl += "&commentPage=" + commentPage;
	}	
					
	location.href = strUrl;
}
function goPageCartoon(page) {
	var frm = document.getElementById('articleListForm')
	
	var searchQueryString = frm.searchQueryString.value;
	var nCategory = frm.category.value;
	var searchBlock = frm.searchBlock.value;
	
	//var strUrl = location.pathname + '?page=' + page + '&searchBlock=' + searchBlock + searchQueryString;
	var strUrl = 'index?page=' + page + '&searchBlock=' + searchBlock + searchQueryString;
			
	if( nCategory.length > 0 && !isNaN(nCategory) )
		strUrl += "&category=" + nCategory;
	
	//view's innerlist

	if( typeof(frm.articleID) != 'undefined' ) {
		var articleID = frm.articleID.value;	
		if( articleID.length > 0 && !isNaN(articleID) )
			strUrl += "&articleID=" + articleID;
	}
	
	if( typeof(frm.commentPage) != 'undefined' ) {
		var commentPage = frm.commentPage.value;	
		if( commentPage.length > 0 && !isNaN(commentPage) )
			strUrl += "&commentPage=" + commentPage;
	}	
					
	location.href = strUrl;
}

function changeSearchBlock(searchBlock) {
	var frm = document.getElementById('articleListForm')
	
	var searchQueryString = frm.searchQueryString.value;
	var nCategory = frm.category.value;
	
	var strUrl = location.pathname + '?page=1&searchBlock=' + searchBlock + searchQueryString;
			
	if( nCategory.length > 0 && !isNaN(nCategory) )
		strUrl += "&category=" + nCategory;
		
	//view's innerlist

	if( typeof(frm.articleID) != 'undefined' ) {
		var articleID = frm.articleID.value;	
		if( articleID.length > 0 && !isNaN(articleID) )
			strUrl += "&articleID=" + articleID;
	}
	
	if( typeof(frm.commentPage) != 'undefined' ) {
		var commentPage = frm.commentPage.value;	
		if( commentPage.length > 0 && !isNaN(commentPage) )
			strUrl += "&commentPage=" + commentPage;
	}	
					
	location.href = strUrl;
}

function goCommentPage(commentPage) {	
	var frm = document.getElementById('articleListForm')
	
	var searchQueryString = frm.searchQueryString.value;
	var nCategory = frm.category.value;
	var articleID = frm.articleID.value;
	var page = frm.page.value;
	var searchBlock = frm.searchBlock.value;
	
	//var strUrl = location.pathname + '?articleID=' + articleID + '&page=' + page + '&searchBlock=' + searchBlock + '&commentPage=' + commentPage + searchQueryString;
	var strUrl = location.pathname + '?articleID=' + articleID + '&page=' + page + '&searchBlock=' + searchBlock + '&commentPage=' + commentPage + searchQueryString + '#place_comment';
			
	if( nCategory.length > 0 && !isNaN(nCategory) )
		strUrl += "&category=" + nCategory;
					
	location.href = strUrl;
			
}

// search characterNick
function searchFriend(page, targetForm) {
	if (null == page) page = 1;
	if (null == targetForm) targetForm = 'searchFriend';
		
	var frm = document.getElementById(targetForm);
	var nick = frm.nickname.value.trim();

	if (null == nick || '' == nick) {
		//alert("검색할 캐릭터명을 입력해주세요.");
		return;
	}
	/*
	var reg = new RegExp("[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ]+", "ig");
	if (reg.test(nick)) {
		alert("특수문자를 검색어로 사용할 수 없습니다.");
		frm.nickname.focus();
		return;
	}
	*/
	frm.page.value = page;
	frm.nickname.value = nick;
	
	var params = Form.serialize(targetForm);
	location.href = '/board/character/characterlist?' + params;
}

//init personal main
/*
function initNewPersonalMain(){
	if(isLogged()=='true'){
		new Ajax.Request(unescape('/personalmain/actionlist'), {
				method:'post',
				encoding: 'UTF-8',
				parameters: '', 
				onSuccess: function(request) {	
					if(request.responseText.trim() != '<!--NoHaveActionLog-->'){
						displayNewPersonalMain(request.responseText);
					} else {
						initNewPersonalMain_noContent();
					}
					
				},
				onFailure: function(request) {
					alert("오류가 발생하였습니다.");
				}
			}
		);
	}
}

function initNewPersonalMain_noContent(){
	new Ajax.Updater('newPersonalMain'
		, '/personalmain/actionAllList'
		,{	method:'get'
			, encoding: 'UTF-8'
			, evalScripts: true
			, onFailure: function()
			{
				alert("오류가 발생하였습니다.");
			}
		}
	);				
}

function initNewPersonalMain_noChar(){
	new Ajax.Request(unescape('/personalmain/actionMyList'), {
			method:'post',
			encoding: 'UTF-8',
			parameters: '',
			onSuccess: function(request) {	
				displayNewPersonalMain(request.responseText);				
			},
			onFailure: function(request) {
				alert("오류가 발생하였습니다.");
			}
		}
	);
}
*/

function displayNewPersonalMain(content){
	$('newPersonalMain').innerHTML = content;
}

function pagingActionLog(option, page, divName){
	var itemListLayer = document.getElementById(divName);
	
	if (typeof itemListLayer == "undefined" || itemListLayer == null) {
		alert("[ERROR] " + divName + " layer not found.");
		return;
	}
	
	var command = '';
	/*
	if(option == 1) {
		command = '/personalmain/actionlist';
	} else if(option == 2) {
		command = '/personalmain/actionMyList';
	} else */if(option == 3) {
		command = '/personalmain/actionToMeList';
	} else if(option == 4) {
		command = '/personalmain/actionOthersList';
	} else if(option == 5) {
		command = '/personalmain/budFam3DaysBirthdayList';
	} else if(option == 6) {
		command = '/personalmain/allwowcombo/friendsPlayList';
	}
	
	var parameters = 'page=' + page;
	new Ajax.Request(unescape(command), {
			method:'post',
			encoding: 'UTF-8',
			parameters: parameters,
			onSuccess: function(request) {
				itemListLayer.innerHTML = request.responseText;
			},
			onFailure: function(request) {
				alert("오류가 발생하였습니다. ");
			}
		}
	);
}

function renderDiv(command, divName) {
		new Ajax.Updater(divName
			, command
			,{	method:'get'
				, encoding: 'UTF-8'
				, evalScripts: true
				, onFailure: function()
				{
					$(divName).innerHTML = '현재 사용자가 많아 정보를 가지고 올 수 없습니다.';
				}
			}
		);			
}

function birthPaging(page, birthPageSize, birthListSize){
	for (var i=1; i < birthListSize+1; i++){
		$('birthLi' + i).style.display = "none";
	}
	
	for (var j=(page-1)*birthPageSize + 1 ; j < page*birthPageSize + 1 && j <= birthListSize; j++){
		$('birthLi'+j).style.display = "block";
	}
	$('birthPage').innerHTML = page;
}
function birthPageAction(toAct, birthPageSize, birthListSize){
	var page = $('birthPage').innerHTML;
	var birthLastPage = Math.floor(((birthListSize-1)/birthPageSize)+1);
	page = parseInt(page);
	if ( toAct == 'prev' ) {
		if ( page == 1 ) {
			birthPaging(birthLastPage, birthPageSize, birthListSize);
		} else {
			birthPaging(page-1, birthPageSize, birthListSize);
		}
	} else { // toAct == 'next' 
		if ( page == birthLastPage ) {
			birthPaging(1, birthPageSize, birthListSize);
		} else {
			birthPaging(page+1, birthPageSize, birthListSize);
		}
	}
}
