var xmlHttp			=	false;
var google_ad_client	=	'pub-9267243209136393';
var google_ad_slot		=	'8023528827';
var google_ad_width	=	728;
var google_ad_height	=	90;
				
/* 아작스 객체 생성 */
function ajaxCreate() {
	xmlHttp	=	window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
}

/* 아작스 처리 */
function ajaxRequest(div,actionfile,param,xml) {
	if(!xmlHttp) ajaxCreate();

	xmlHttp.open('post',actionfile,false);
	xmlHttp.setRequestHeader('content-type','application/x-www-form-urlencoded');
	xmlHttp.send(param);

	if(!xmlHttp) {
		error('Ajax not support.');
		return;
	}

	if(xml) {
		eval(div +'(xmlHttp)');
	} else {
		if(!div) return xmlHttp.responseText;

		document.getElementById(div).innerHTML	=	xmlHttp.responseText;
	}
}

/* 공백 제거 */
String.prototype.trim = function() {
    return this.replace(/(^[ \f\n\r\t　]*)|([ \f\n\r\t　]*$)/g, "");
}

/* 입력값 검사 */
function errorMessage(obj,message) {
	return !obj.trim() ? error(((message.indexOf('.') == -1) ? message + ' 입력하여 주세요.' : message),0,obj) : true;
}

/* 로그인 체크 */
function loginCheck(f) {
	var emailAvail	=	/^[._a-zA-Z0-9-]+@[._a-zA-Z0-9-]+\.[a-zA-Z]+$/;

	if(!errorMessage(f.userEmail.value,'이메일을')) return false;
	if(!emailAvail.test(f.userEmail.value)) {
		error('올바른 이메일 주소가 아닙니다.');
		return false;
	}
	if(!errorMessage(f.userPasswd.value,'비밀번호를')) return false;
}

/* 로그인 상태 */
function loginStatus() {
	if(getCookie('YARIKURI')) {
		return true;
	} else {
		error('로그인 후 이용하여 주세요.');
		return false;
	}
}

/* 로그아웃 */
function logoutProcess() {
	setCookie('YARIKURI',null,-1);
	location.href	=	location.href;
}

/* 불량 단어 제거 */
function illigalWordsCheck(str) {
	var strIlligal			=	'*야리꾸리*|*야동*|\\b섹스';
	var strReplace		=	new RegExp(strIlligal.replace(/[^a-z0-9\\\|]/gi,''),'gim');
	var strNew			=	str.replace(strReplace,function($0) { return $0.replace(/[a-z0-9]/gi,'*'); });
	
	if(str != strNew) error('We have detected inappropriate word.');
	
	return strNew;
}

/* 이미지 리사이즈 */
function imageResize(obj,size) {
	if(!size) {
		obj.width		=	"100%";
	} else {
		if(w=eval(obj.width) > size) obj.width = size;
	}
}

/* 메시지 출력 */
function error(msg,opt,f) {
	msg	=	msg ? msg : '로그인 후 이용하여 주세요.';

	if(opt) {
		return confirm(msg);
	} else {
		try {
			layerPopup(msg);
		} catch(ex) {
			alert(msg);
		}
		
		if(f) f.focus();
	}
}

/* 레이어 팝업 */
function layerPopup(msg,w,h,flag) {
	if(flag == 2) {
		var w			=	w ? parseInt(w+10) : 290;
		var h			=	h ? parseInt(h+38) : 380;
	} else {
		var w			=	290;
		var h			=	flag ? 380 : 200;
	}

	var position			=	layerPosition(w,h);
	
	layerShow();

	var html			=	'<iframe src="/include/layer.php?msg='+ encodeURIComponent(msg) +'&flag='+ (flag ? flag : "") +'&w='+ w +'&h='+ h +'" width="'+ w +'" height="'+ h +'" scrolling="no" frameborder="0" allowtransparency="true"></iframe>';

	document.getElementById('divLayer').innerHTML	=	html;
}

/* 레이어 팝업 위치 선정 */
function layerPosition(w,h) {
	if(!document.getElementById('divLayer')) {
		var divNew;
		var divName	=	['divLayer','divLayerBg'];

		for(var i=0;i<divName.length;i++) {
			divNew		=	document.createElement('div');
		
			divNew.setAttribute('id',divName[i]);
			document.body.appendChild(divNew);
		}
	}
	
	var obj				=	document.getElementById('divLayer');
	var objBg			=	document.getElementById('divLayerBg');
	var cWidth			=	document.documentElement.clientWidth;
	var cHeight			=	document.documentElement.clientHeight;
	var sHeight			=	document.documentElement.scrollHeight;
	var sScroll			=	document.documentElement.scrollTop;

	objBg.style.cssText	=	'margin:0;padding:0;position:absolute;top:0;left:0;width:100%;height:'+ ((cHeight > sHeight) ? cHeight : sHeight)+'px;z-index:1165;background:#000;filter:alpha(opacity=75);opacity:0.75;-moz-opacity:0.75;';
	obj.style.cssText		=	'margin:0;padding:0;position:absolute;z-index:6244;';
	obj.style.left		=	Math.ceil((cWidth-w)/2) +'px';
	obj.style.top		=	Math.ceil((cHeight-h)/2+sScroll) +'px';
}

/* 레이어 팝업 노출 제어 */
function layerShow() {
	var divName	=	['divLayer','divLayerBg'];
	var obj;
	
	for(var i=0;i<divName.length;i++) {
		obj		=	document.getElementById(divName[i]);

		obj.innerHTML		=	'';
		obj.style.display	=	(obj.style.display != 'block') ? 'block' : 'none';
	}
	
	if(isIE()) {
		if(!isIE7()) {
			var sel		=	document.getElementsByTagName('select');
	
			for(var j=0;j<sel.length;j++) {
				sel[j].style.visibility	=	(obj.style.display != 'block') ? 'visible' : 'hidden';
			}
		}
		
		var player	=	document.getElementsByTagName('object');
		
		for(var k=0;k<player.length;k++) {
			if(player[k].id == 'objPlayer') {
				player[k].style.visibility	=	(obj.style.display != 'block') ? 'visible' : 'hidden';
			}
		}
	}
}

/* 매개 변수 조합 */
function linkParameter(except) {
	var obj		=	location.href;
	var param	=	'';

	if(obj.indexOf('?') == -1 && obj.indexOf('menu=') != -1) return '';

	if(obj.indexOf('menu=') == -1 && except.indexOf('menu') == -1) {
		var menu	=	document.getElementById('menuList').getElementsByTagName('li');

		for(var j=1;j<menu.length;j++) {
			if(menu[j].className == 'mouseOver') {
				param	=	'&menu='+ menu[j].onclick.toString().replace(/[^0-9]/gi,'');
			}
		}
	}

	var devide	=	obj.substr(obj.indexOf('?')+1).split('&') ? obj.substr(obj.indexOf('?')+1).split('&') : [];
	var tmp

	for(var i=0;i<devide.length;i++) {
		tmp	=	devide[i].split('=');
		param	+=	((except ? except : '').indexOf(tmp[0]) == -1 && tmp[1]) ? '&'+ tmp[0] +'='+ tmp[1] : '';
	}

	return param;
}

/* 회원 정보 수정 */
function userModify() {
	if(!loginStatus()) return;
}

// 파일명을 변경
function thisFile(a) {
	var thisHref		=	location.href.split('/');
	var thisReFile	=	thisHref[thisHref.length-1].replace(/(\?(.)*)/gi,'');
	var thisLocate	=	thisReFile.split('.');
	var thisName	=	thisLocate[0].replace(/(_(.)*)/gi,'');

	return a ? thisName + '_' + a +'.'+thisLocate[1] : thisName + '.'+thisLocate[1];
}

/* 홈 링크 */
function linkHome() {
	location.href	=	'/';
}

/* 글쓰기 링크 */
function linkWrite() {
	if(!loginStatus()) return;
	location.href	=	'/blog/blog_write.php?mode=write'+ linkParameter('mode');
}

/* 관리자 링크 */
function linkAdmin(idx) {
	if(!loginStatus()) return;
	
	var page	=	['member','menu'];
	
	location.href	=	'/admin/'+ page[idx] +'/'+ page[idx] +'.php';
}

/* 메뉴 링크 */
function linkMenu(menu) {
	location.href	=	'/page/'+ menu +'/1';
}

/* 뷰 링크 */
function linkView(bbs,menu) {
	if(!bbs) {
		error('권한이 없습니다.');
		return;
	}
	
	location.href	=	'/blog/blog_view.php?bbs='+ bbs + (menu ? '&menu='+ menu + linkParameter('bbs,mode,menu') : linkParameter('bbs,mode'));
}

/* 수정 링크 */
function linkEdit() {
	location.href	=	'/blog/blog_write.php?mode=edit'+ linkParameter();
}

/* 삭제 링크 */
function linkDelete() {
	if(!error('삭제하시겠습니까?',1)) return;
	location.href	=	'/blog/blog_proc.php?mode=delete'+ linkParameter();
}

/* 리스트 링크 */
function linkList() {
	location.href	=	'/blog/blog.php?'+ linkParameter('bbs,mode').substr(1);
}

/* 페이징 링크 */
function linkPage(page) {
	location.href	=	thisFile() +'?page='+ page + linkParameter('page');
}

/* 댓글 쓰기 */
function commentWrite(obj) {
	if(!loginStatus()) return;
	if(!errorMessage(obj.form.content.value,'댓글을')) return;
	ajaxRequest('commentResult','/blog/blog_comment.php','mode=write&content='+ encodeURIComponent(obj.form.content.value) + linkParameter('mode'),true);
	obj.form.reset();
	obj.form.content.focus();
}

/* 댓글 삭제 */
function commentDelete(ment) {
	if(!error('삭제하시겠습니까?',1)) return;
	ajaxRequest('commentResult','/blog/blog_comment.php','mode=delete&ment='+ ment + linkParameter('mode'),true);
}

/* 댓글 페이징 */
function commentPage(page) {
	ajaxRequest('comment','/blog/blog_comment.php','page='+ (page ? page : 1) + linkParameter('mode'));
}

/* 댓글 결과 */
function commentResult(xmlHttp) {
	var xmlData	=	xmlHttp.responseText.trim();
	
	if(xmlData.substr(0,6) == '<table') {
		document.getElementById('comment').innerHTML	=	xmlData;
	} else {
		error('권한이 없습니다.');
	}
}

/* 검색 링크 */
function linkSearch(obj) {
	var word		=	obj.word.value.trim();
	var param		=	linkParameter('bbs,page,mode,word');
	var variable		=	word ? 'word='+ encodeURIComponent(word) + param : param.substr(1);
	location.href	=	'/blog/blog.php?' + variable;
	return false;
}

/* 플래시 출력 */
function showFlash(flashUrl,flashWidth,flashHeight,flashDiv) {
	var flashPath,flashVars;
	var classId			=	"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
	var codeBase		=	"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0";
	var pluginsPage	=	"application/x-shockwave-flash";
	var embedType	=	"application/x-shockwave-flash";
	var pluginsPage	=	"http://www.macromedia.com/go/getflashplayer";

	var flashHtml		=	"";

	flashHtml			+=	'<object id="objFlash" classid="'+ classId +'" codebase="'+ codeBase +'" width="'+ flashWidth +'" height="'+ flashHeight +'">';
	flashHtml			+=	'	<param name="movie" value="' + flashUrl + '" />';
	flashHtml			+=	'	<param name="quality" value="high" />';
	flashHtml			+=	'	<param name="allowScriptAccess" value="always" />';
	flashHtml			+=	'	<param name="wmode" value="transparent" />';
	flashHtml			+=	'	<embed src="'+ flashUrl + '" quality="high" wmode="transparent" width="'+ flashWidth +'" height="'+ flashHeight +'" type="' + embedType + '" pluginspage="' + pluginsPage + '" />';
	flashHtml			+=	'</object>';

	if(flashDiv) {
		document.getElementById(flashDiv).innerHTML	=	flashHtml;
	} else {
		document.write(flashHtml);
	}
}

/* 동영상 출력 */
function showMovie(movieUrl,movieWidth,movieHeight,movieDiv,movieUI,moviePlay) {
	var classId			=	"clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6";
	var playUI			=	movieUI ? "none" : "full";		//	스크린 모드
	var playMode		=	moviePlay ? "false" : "true";	//	자동 플레이
	var movieHtml		=	"";

	movieHtml			+=	'<object width="'+ movieWidth +'" height="'+ movieHeight +'" id="objPlayer" classid="'+ classId +'">';
	movieHtml			+=	'	<param name="autostart" value="'+ playMode +'">';
	movieHtml			+=	'	<param name="url" value="'+ movieUrl +'">';
	movieHtml			+=	'	<param name="volume" value="70">';
	movieHtml			+=	'	<param name="showcontrols" value="true">';
	movieHtml			+=	'	<param name="defaultframe" value="content">';
	movieHtml			+=	'	<param name="uiMode" value="'+ playUI +'">';
	movieHtml			+=	'	<param name="enablecontextmenu" value="false">';
	movieHtml			+=	'	<param name="fullscreen" value="false">';
	movieHtml			+=	'	<param name="enabled" value="true">';
	movieHtml			+=	'	<param name="stretchtofit" value="true">';
	movieHtml			+=	'</object>';

	if(movieDiv) {
		document.getElementById(movieDiv).innerHTML	=	movieHtml;
	} else {
		document.write(movieHtml);
	}
}

/* 익스플로러 구분 */
function isIE() {
	return (navigator.appName == 'Microsoft Internet Explorer') ? true : false;
}

/* 익스플로러7 구분 */
function isIE7() {
	var flag				=	false;
	var arrVerStr		=	window.navigator.appVersion.split("; ");

	if(arrVerStr.length >= 4) {
		var arrIEVer	=	arrVerStr[1].split(" ");
		
		if(arrIEVer[1] >= 7.0) {
			flag			=	true;
		}
	}

	return flag;
}

/* 이벤트 추가 */
function addEvent(ev,fnc,obj) {
	obj		=	obj ? obj : window;
	isIE() ? obj.attachEvent(ev,fnc) : obj.addEventListener(ev.replace("on",""),fnc,false);
}

/* 쿠키 굽기 */
function setCookie(name,value,expiredays) {
	var todayDate = new Date();
	todayDate.setDate(todayDate.getDate() + expiredays);
	document.cookie = name + "=" + escape(value) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}

/* 쿠키 읽기 */
function getCookie(name){
    var nameOfCookie = name + "=";
    var x = 0;
    while(x <= document.cookie.length) {
        var y = (x+nameOfCookie.length);
        if(document.cookie.substring(x,y) == nameOfCookie) {
            if((endOfCookie=document.cookie.indexOf(";",y)) == -1) {
                endOfCookie = document.cookie.length;
            }
            return unescape(document.cookie.substring(y,endOfCookie));
        }
        x = document.cookie.indexOf(" ",x)+1;
        if(x == 0)
        break;
    }

    return "";
}