// 브라우저 정보
var BrowserInfo={};
var ua=navigator.userAgent.toLowerCase();
BrowserInfo.isMozilla=(typeof document.implementation!='undefined')&&(typeof document.implementation.createDocument!='undefined')&&(typeof HTMLDocument!='undefined');
BrowserInfo.isIE=window.ActiveXObject?true:false;
BrowserInfo.isIE6 = ((ua.indexOf("msie") != -1) && (parseInt(navigator.appVersion,10) == 4) && (ua.indexOf("msie 6.")!=-1) )?true:false;
BrowserInfo.isFirefox=(ua.indexOf("firefox")!=-1);
BrowserInfo.isSafari=(ua.indexOf("safari")!=-1);
BrowserInfo.isOpera=(typeof window.opera!='undefined');
BrowserInfo.isMacOS=(navigator.platform.indexOf("Mac")!=-1);
BrowserInfo.getDocumentWidth=function(){return(document.documentElement&&document.documentElement.scrollWidth)||document.body.scrollWidth;};
BrowserInfo.getDocumentHeight=function(){return(document.documentElement&&document.documentElement.scrollHeight)||document.body.scrollHeight;};
BrowserInfo.getClientWidth=function(){return(window.innerWidth||(document.documentElement&&document.documentElement.clientWidth)||(document.body&&document.body.clientWidth)||0);};
BrowserInfo.getClientHeight=function(){return(window.innerHeight||(document.documentElement&&document.documentElement.clientHeight)||(document.body&&document.body.clientHeight)||0);};
BrowserInfo.getScrollTop=function(){return(document.documentElement&&document.documentElement.scrollTop)||(document.body&&document.body.scrollTop)||0;};
BrowserInfo.getScrollLeft=function(){return(document.documentElement&&document.documentElement.scrollLeft)||(document.body&&document.body.scrollLeft)||0;};

Class={
	greatestId:0,
	create:function(methods){
		var newClass=function(){
			this._uniqueId=Class.greatestId++;
			this.initialize.apply(this,arguments);
		};
		Object.extend(newClass,{
			createSubClass:function(extraMethods){
				var subClass=Class.create(this.prototype);
				subClass.superClass=this;
				subClass.addMethods(extraMethods);
				return subClass;
			},
			addMethods:function(methods){
				if(!methods){ return; }
				var mergedClassMethods;
				if(methods.classMethods){
					Object.extend(this.prototype.classMethods,methods.classMethods);
					Object.extend(this,methods.classMethods);
					mergedClassMethods=this.prototype.classMethods;
				}
				Object.extend(this.prototype,methods);
				if(mergedClassMethods){this.prototype.classMethods=mergedClassMethods;}
			}
		}
	);
	newClass.prototype.toString=function(){
		return'[ClassInstance:'+this._uniqueId+']';
	};
	newClass.prototype.classMethods={};
	newClass.addMethods(methods);
	newClass.prototype.constructor=newClass;
	return newClass;
	}
};

// ajax common lib
var ajax = {
	// ajax 파서
	_parser: function() {
		var links = document.getElementsByTagName('a');

		for (var i = 0; i < links.length; i++) {
			var el = links[i];
			if(el.getAttribute("ajax")) {
				var link = el.getAttribute("ajax");
				el.href= '#ajax:'+link;
				var args = link.split(':');
				var method = args.shift(); var array;

				for (var s = 0; s < args.length; s++){
					if(s==0) array = '"'+args[s]+'"'; 
					else array += ',"'+ args[s] + '"';
				}
				try{
					if(el.onclick == null){	el.onclick = new Function( "ajax."+ method +"(new Array(" + array + ")); return false;" ); }
				}catch(e){
					//alert(array+e);
				}
			}
		}
	},
	_parsing: function() {
		var links = document.getElementsByTagName('a');
		for (var i = 0; i < links.length; i++) {
			var el = links[i];
			if((el.getAttribute("rel") == "ajax")){
				var link = el.getAttribute("href");
				var args = link.split(':');
				var method = args.shift(); var array;
				for (var s = 0; s < args.length; s++){ 
					if(s==0) array = '"'+args[s]+'"'; 
					else array += ',"'+ args[s] + '"';
				}
				try{
					if(el.onclick == null){	el.onclick = new Function( "ajax."+ method +"(new Array(" + array + ")); return false;" );}
				}catch(e)	{
				}
			}
		}
	}	
}

Object.extend(Element,{
						// 해당 Element 하위에 클래스 이름을 찾아 해당 Element 리턴
						getDescendantByClassName:function(element,className){
							element=$(element);
							if(element&&element.childNodes){
								for(var i=0;i<element.childNodes.length;i++){
									var elem=element.childNodes[i];
									if(elem.nodeType!=1)continue;
									if(elem.className&&Element.hasClassName(elem,className)){
										return elem;
									}
									var result=Element.getDescendantByClassName(elem,className);
									if(result){return result;}
								}
							}
							return null;
						},
						getDescendantsByClassName:function(element,className){
							return document.getElementsByClassName(className,element);
						},
						getDescendantByNodeName:function(element,nodeName){
							element=$(element);
							nodeName=nodeName.toLowerCase();
							if(element&&element.childNodes){
								for(var i=0;i<element.childNodes.length;i++){
									var elem=element.childNodes[i];
									if(elem.nodeName.toLowerCase()==nodeName){return elem;}
									var result=Element.getDescendantByNodeName(elem,nodeName);
									if(result){return result;}
								}
							}
							return null;
						},
						isNodeEqualOrChildOf:function(childNode,parentNode){
							while(childNode){
								if(childNode==parentNode){return true;}
								childNode=childNode.parentNode;
							}
							return false;
						}
					}
);

// trim
String.prototype.trim=function(){return this.replace(/^\s*|\s*$/g,"");};
// is argument
String.prototype.isArgument=function(){ return /^([a-zA-Z]){1,}=([0-9]){1,}$/.test(this);}
// email
String.isEmail=function(text){var regexp=/^([a-zA-Z0-9_.\-+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;return regexp.test(text);}
String.prototype.truncate=function(length,truncation){length=length||30;truncation=truncation===undefined?'...':truncation;return this.length>length?this.slice(0,length-truncation.length)+truncation:this;};
String.prototype.br2nl= function() {  var objStrip = new RegExp(); objStrip = /<br>/gi; return this.replace(objStrip, "\r\n");}

var Utils = Class.create();
Utils.prototype = {
	initialize:function(){
	},
	// Fields 체크
	validateFields:function(fields){
		for(var id in fields){
			var field=$(id);
			for(var validation_type in fields[id]){
				switch(validation_type){
					case'empty':
						if(field.value.length==0){
							this.errorInField(field,fields[id][validation_type]);
							return false;
						}
					break;
					default:
					return false;
					break;
				}
			}
		}
		return true;
	},
	// 에러 처리
	errorInField:function(field,error_message_details){
		if(error_message_details.message){
			Dialog.message(error_message_details.message);
		}else{
			var name=error_message_details.name;
			if(!name){	name=id;}
			Dialog.message(name);
		}
	},
	// 쿠키세팅
	setCookie:function(cookieName, cookieValue, expires, path, domain, secure) {
		document.cookie =
			escape(cookieName) + '=' + escape(cookieValue)
			+ (expires ? '; expires=' + expires.toGMTString() : '')
			+ (path ? '; path=' + path : '')
			+ (domain ? '; domain=' + domain : '')
			+ (secure ? '; secure' : '');
	}
}
 
var Utils = new Utils();
Utils.Tooltip = Object.extend(Utils, {
	blogPreview:function(bbs_name,b_no,nickname,subject,reply,img,content,date, obj) {
		var pnLeft = 10; // panel 왼쪽으로 나온만큼
		var pnTop = 15;  // 위로 올라온만큼

		$("preview-bbs").innerHTML = bbs_name;
		$("preview-number").innerHTML = b_no;
		$("preview-author").innerHTML = nickname;
		$("preview-subject").innerHTML = subject;
		$("preview-text").innerHTML = content;
		$("preview-date").innerHTML = date;
		
		if (img && img != "null")	{
			$("preview-img").style.display = "block";
			$("preview-img").innerHTML = "<img width='100' height='67' alt='' border='0' src=" +img + ">"; 
		}else{
			$("preview-img").style.display = "none"; 
		}

		if (reply && reply != "null")	{
			$("preview-reply").style.display = "block";
			$("preview-reply").innerHTML = "(" + reply + ")";
		}else{
			$("preview-reply").style.display = "none";
		}		  

		if (subject && subject != "null")	{
			$("preview-subject").style.display = "block";
			$("preview-subject").innerHTML = subject;
		}else{
			$("preview-subject").style.display = "none";
		}		
		
 
		if (this.blogPreviewLayer == "" || this.blogPreviewLayer == null) {
			this.blogPreviewLayer = $("blog-preview");
		}

		// 미리보기 나타낼 최근글의 위치 값 구하기.	
		var pos = Position.cumulativeOffset(obj);
		// 최근글 쪽으로 레이어 이동 시키기.

		this.setPosition( this.blogPreviewLayer, pos[0], pos[1]+pnTop );

		// 박스 위치 변형
		var inViewPort = this.isInViewPort(this.blogPreviewLayer);
		
		this.blogPreviewLayer.style.display = "block";
	
		// 스크롤값이 포함된 현재 위치 구하기.
		var tmpRos = Position.realOffset(this.blogPreviewLayer);
		// 레이어의 가로,세로 길이 구하기. 
		var tmpDms = Element.getDimensions(this.blogPreviewLayer);

		// 최근글 위치값 구하기.
		var tmpObjPos = Position.cumulativeOffset(obj);
		var tmpVpt = this.getViewport();
		
		var tempMarginLeft;
		
		// 레이어가 오른쪽으로 오바됐으면,  왼쪽으로 위치 변경.
		if (inViewPort[0] > 0) {
			pos[0] = tmpRos[0] + tmpVpt[0] - tmpDms.width - pnLeft*2;
			
		} else if (inViewPort[0] < 0) {
			pos[0] = tmpRos[0];
		}

		tempMarginLeft = 300 - pos[0] - tmpDms.width + tmpObjPos[0];

		if (tempMarginLeft < 10) {
			tempMarginLeft = 10;	
		} else if (tempMarginLeft > 240) {
			tempMarginLeft = 240;
		}

		$('arrow-up').style.marginLeft = tempMarginLeft+'px';
		$('arrow-down').style.marginLeft = tempMarginLeft+'px';

		// 세로로 오버 됐으면 레이어를 밑으로 위치 변경. 
		if (inViewPort[1]>0) {
			pos[1] = pos[1] - tmpDms.height - pnTop;
			$('arrow-up').style.display = 'none';
			$('arrow-down').style.display = 'block';
		} else {
			$('arrow-up').style.display = 'block';
			$('arrow-down').style.display = 'none';
		}
		this.blogPreviewLayer.style.display = "none";
		
		this.setPosition( this.blogPreviewLayer, pos[0]+pnLeft, pos[1]+pnTop );
		// 박스 위치 변형 END
	
		this.blogPreviewLayer.style.display = "block";
	},
	// 미리보기 감추기
	blogPreviewHide: function() {
		if (!this.blogPreviewLayer) this.blogPreviewLayer = $("blog-preview");
		this.blogPreviewLayer.style.display = "none";
	},
	setPosition:function( obj, x, y ) {

		obj.style.left = x+'px';
		obj.style.top = y+'px';
	},
	isInViewPort:function(obj) {
		var result = new Array(2);
		// result[0] : 1-오른쪽 초과, -1 왼쪽 초과
		// result[1] : 1-아래쪽 초과, -1 윗쪽 초과
		result[0] = 0; 
		result[1] = 0;
	
		var tempDisplay = obj.style.display;
		obj.style.display = 'block';
		
		var objSize = Element.getDimensions(obj); // 객체의 가로 세로 길이.
		var objPage = Position.page(obj); // 페이지 내에서의 가로 세로 값.
	
		if (objPage[0]+objSize.width > BrowserInfo.getClientWidth()) {
			result[0] = 1;
		} else if (objPage[0] < 0) {
			result[0] = -1;	
		}
	
		if (objPage[1]+objSize.height > BrowserInfo.getClientHeight()) {
			result[1] = 1;	
		} else if (objPage[1] < 0) {
			result[1] = -1;	
		}

		obj.style.display = tempDisplay;
	
		return result;
	},
	getViewport:function() {
		var w=0;
		var h=0;
		
		if(window.innerWidth) w=window.innerWidth;
		if(document.documentElement.clientWidth){
			var w2 = document.documentElement.clientWidth;
			if(!w || w2 && w2 < w) w=w2;
		}else if(document.body){
			w=document.body.clientWidth;
		}
	
		if(window.innerHeight) h=window.innerHeight;
		if(document.documentElement.clientHeight) h=document.documentElement.clientHeight;
		else if(document.body) h=document.body.clientHeight;
	
		return [w,h];
	},
	// 리스트 삭제 또는 리프레쉬 역활.
	commonAction:function(fields) {
		fields['query'] += '&state=' + $(fields['type'] + 'State').value;
		ajax._send(fields);
	},
	deleteAction:function(fields) {
		if(confirm("정말 삭제하시겠습니까?")) {
			fields['query'] += '&state=' + $(fields['type'] + 'State').value;
			ajax._send(fields);			
		}
	},	
	uploadSkinImage : function(path, name){
		$('thum_path').value = path;
		$('thum_name').value = name;
	}
})

Utils.Scroll = Class.create();
Utils.Scroll.prototype = {
	obj : null,
	startPosition : null,
	
    initialize: function(obj){
		this.obj = obj;
		var pos = Position.cumulativeOffset($('elhtm'));
		this.startPosition = {top : $('optop').offsetHeight, left : pos[0] };
		Element.setStyle(this.obj, {top: this.startPosition.top + 'px', left : this.startPosition.left + 'px', position: 'absolute'});
		
		this.eventScroll = this.scroll.bindAsEventListener(this);
		Event.observe(window, "resize", this.eventScroll);
		Event.observe(window, "scroll", this.eventScroll);
    },
	scroll : function(e){
		var pos = Position.cumulativeOffset($('elhtm'));
		new Effect.MoveBy(this.obj, this.startPosition.top + BrowserInfo.getScrollTop(), pos[0],{duration:0.2, mode: 'absolute'} );
	}
}

var historyDiv;
var historyAddress = "home";
var historyPosition = "top";

Object.extend(ajax, {
	_send: function(fields) {

		var parameters = '';
		var oncomplete = '';
		if((fields['form']!= "") && (fields['form'] != undefined)) parameters = Form.serialize($(fields['form']));
		if(fields['query'] != "") fields['url'] += '?'+fields['query']+'&nocache='+Math.random();
		if(fields['onComplete'] != "") oncomplete = fields['onComplete'];
		// loading
		this.StartProgress();
		var myAjax = new Ajax.Updater({success: fields['div']}, fields['url'],	{ method : fields['method'],	parameters : parameters, onFailure : this.reportError,	onSuccess : this.addHistory, onComplete : oncomplete, asynchronous:true,evalScripts:true});
		// history info
		historyDiv = fields['div'];
		historyPosition	    = (fields['target'] == "self") ? fields['target'] : fields['div'];
		historyAddress = "post:" + fields['url'] + ":" + fields['form'] + ":" + fields['method'] + ":" + fields['query'] + "&branch=:" + fields['div'];
	    if((historyDiv=="opm") && historyPosition != "history") {
			dhtmlHistory.add(historyAddress, '');
	        historyDiv = "";
		}
	},
	addHistory:function(obj) {
	    if(historyPosition != "" && historyPosition != "self" && navigator.userAgent.toLowerCase().indexOf('msie')!=-1) {
    	    historyPosition = "";
    	}
		ajax.EndProgress();
	},
	reportError:function(obj){
	},
	// 바로가기 리스트
	_list:function(fields){
		if(!fields['div']){
			Element.hide('ohpylist');
			Event.stopObserving(document, 'mouseup', ajax._list);
			return;
		}
		$(fields['div']).setStyle({zIndex: '999'});
		Event.observe(document, 'mouseup', ajax._list);
		this._send(fields);
	},
	// 검색
	_search:function(array) {
		$("elsch").value = $("elsch").value.trim();
		if(!Utils.validateFields({elsch:{empty:{name:'검색할 단어를 입력해주세요.'}}})){	
			return;	
		}
		this.post(array);
	},
	// URL 체크
	_checkUrl:function(array) {
		$('op_title').value = $('op_title').value.trim();
		if(!Utils.validateFields({op_title:{empty:{name:'오피 타이틀을 입력하세요.'}}})){ return; }
		if($('url_valid').value != "Y"){
			Dialog.message('사용할수 없는 URL입니다.');
			return;
		}
		this.post(array);
	},
	// 로그인
	checkLogin:function(array) {
		if(!Utils.validateFields({u_id:{empty:{name:'아이디를 입력해주세요.'}},u_pwd:{empty:{name:'비밀번호를 입력해주세요.'}}})){
			return;
		}else{
			var preDate = new Date();
			var nextDate = new Date();
			nextDate.setMonth(nextDate.getMonth()+1);	
		}

		//보안접속시 submit으로 함.
		if(typeof $('id-safe-check') != "undefined" && $('id-safe-check').checked == true) {
			var theform = document.loginForm;
			theform.target ="_self";
			
			if(typeof $('op_no') != "undefined"){
				if($('op_no').value == 159843){
					// TODO : 이부분을 https로 변경할 것. by 식.
					theform.action = "https://www.2ndrive.com:8443/opele/?control=Lgn&op_no=159843&branch=ssl_login";
				}
			}else{
				// TODO : 이부분을 https로 변경할 것. by 식.
				theform.action = "https://www.ohpy.com/opele/?control=Lgn&op_no=2&branch=ssl_login";
			}
			
			var szURI =  document.location.href;
			szURI = (szURI.indexOf("#") != -1) ? szURI.substring(0,szURI.indexOf("#")) : szURI;
			$('returnURI').value = szURI;
			theform.submit();
		} else {
			this.post(array);
		}
	},
	clipboard:function(obj,msg){
		if(BrowserInfo.isIE){
			// 글립보드 넣기
			if(obj.innerHTML != ""){
				window.clipboardData.setData('Text', obj.innerHTML);
			}else{
				window.clipboardData.setData('Text', obj.value);
			}
			Dialog.message2(msg);
		}
	},
	_confirm: function(fields,msg) {
		if(confirm(msg)){
			this._send(fields);
		}
	},
	_storeMySkin: function(fields){
		if(!Form.Element.getValue('set_name').trim()){
			alert('스킨이름을 입력해주세요.');
			return;
		}
		if(!Form.Element.getValue('thum_path') || !Form.Element.getValue('thum_name')){
			alert('스킨 썸네일을 등록해주세요.');
			return;
		}
		if(!Form.Element.getValue('set_info').trim()){
			alert('스킨 설명를 입력해주세요.');
			return;
		}
		this._send(fields);
	},
	_xtrBbs : function(fields){
		fields['onComplete'] = function(){TagManager.stripLayer($('opm'));}
		this._send(fields);
	}
});

// 공통 update
ajax.post = function(array){
	var uri 				= array[0];
	var form			= array[1];
	var method		= array[2];
	var query			= array[3];
	var div				= array[4];


	historyDiv = div;
	historyAddress = "post:" + array[0] + ":" + array[1] + ":" + array[2] + ":" + array[3] + "&branch=:" + array[4];

	try {
	   historyPosition   = array[5];  
	   if(historyPosition===undefined){
	   		historyPosition = "top";	   	
	   }
    } catch(e) { 
       historyPosition = "top";
    }
    
	var parameters = "";
	if(form != "undefined" && form != "") {
		parameters	= Form.serialize($(form));	
	}

	if(query !== ""){
		var url = uri + '?'+query+'&nocache='+Math.random();
	}else{
		var url = uri;	
	}

	// loading
	ajax.StartProgress();

	var myAjax = new Ajax.Updater({success: div}, url,
									{
										method : method,
										parameters : parameters,
										onFailure : reportError,
										onSuccess : addHistory,
										asynchronous:true,
										evalScripts:true
									});	
}

var addHistory = function(obj) {

	// addHistory 실행이 끝난후 마지막에
    if(historyDiv=="opm") {
		// back function
		if(historyPosition != "history"){
	        dhtmlHistory.add(historyAddress, '');
		}
        historyDiv = "";
    }
    
    if(historyPosition !== "") {
        if(navigator.userAgent.toLowerCase().indexOf('msie')!=-1) {
	    }
        historyPosition = "";
    }
	ajax.EndProgress();
};
ajax.progress = false;
ajax.progressTimer = null;
// load start
ajax.StartProgress = function() { ajax.progress = true; if (ajax.progressTimer != null) window.clearTimeout(ajax.progressTimer); ajax.progressTimer = window.setTimeout(ajax.ShowProgress, 20); }
// load end
ajax.EndProgress = function () { ajax.progress = false; if (ajax.progressTimer != null) window.clearTimeout(ajax.progressTimer); ajax.progressTimer = window.setTimeout(ajax.ShowProgress, 320);}
// show load
ajax.ShowProgress = function() {
	ajax.progressTimer = null;
	var div = $("AjaxProgressIndicator");
	var left = (BrowserInfo.getClientWidth())/2 + BrowserInfo.getScrollLeft();
	var top = (BrowserInfo.getClientHeight())/2 + BrowserInfo.getScrollTop();
	if(ajax.progress && (div != null)) {
		Element.show(div);
		div.style.left = left+'px';
		div.style.top = top+'px';
	} else if (ajax.progress) {
	    div = document.createElement("div");
	    div.id = "AjaxProgressIndicator";
	    div.style.position = "absolute";
	    div.style.verticalAlign = "bottom";
   		div.style.left = left+'px';
		div.style.top = top+'px';
		$(div).setStyle({zIndex: '999'});
		Element.addClassName (div,'loading');
	    document.body.appendChild(div);
	}else if (div){
		Element.hide(div);
	}

}

// array post 변환
ajax.arraypost = function(param){
	var args = param.split(':');
	var method = args.shift();
	for (var s = 0; s < args.length; s++){ 
		if(s==0) array = '"'+args[s]+'"'; 
		else array += ',"'+ args[s] + '"';
	}
	ajax.tmpFunction = new Function( "ajax."+ method +"(new Array(" + array + "));");
	ajax.tmpFunction();
};

// 공통 get
ajax.get = function(uri, query, div){
	var url = uri + '?' + query+ '&nocache='+Math.random();
	var myAjax = new Ajax.Updater({success: div}, url, { method : 'get', onFailure : reportError, asynchronous:true, evalScripts:true});
};

var overPreview = function(obj,szClassName){	var objElement = Element.getDescendantByClassName(obj,szClassName); Element.show(objElement);}
var outPreview = function(obj,szClassName){ var objElement = Element.getDescendantByClassName(obj,szClassName); Element.hide(objElement);	}

var myictbox = function(event,branch,status){
	var activator = $("myictbox");
	if(status == 1){
		activator.style.display = "none";
		Event.stopObserving(document, 'mouseup', function(){myictbox(event,"", 1);}, false);
		return;
	}
	// body onclick
	Event.observe(document, 'mouseup', function(){myictbox(event,"", 1);}, false);
	activator.style.position = "absolute";
	var top = event.clientY + BrowserInfo.getScrollTop();
	var left = event.clientX + BrowserInfo.getScrollLeft();
	// 윈도우 창에 따라 넓이
	if ((left + parseInt(activator.getStyle('width'))) > BrowserInfo.getClientWidth()) {
		left = left - parseInt(activator.getStyle('width'));
	}
	activator.style.top = top + "px";
	activator.style.left = left + "px";
	ajax.get("/opuser/",branch, "myictbox");
};

var reportError	= function(request){
//	alert("error:"+request.responseText); 
};

// script & css 가져오는 모듈
var ScriptLoader = new Object() ;
ScriptLoader.IsLoading = false ;
ScriptLoader.Queue = new Array() ;
ScriptLoader.AddScript = function( scriptPath ){ ScriptLoader.Queue[ ScriptLoader.Queue.length ] = scriptPath ; 	if ( !this.IsLoading ) this.CheckQueue() ;}
function ScriptLoader_OnLoad(){ 	if ( this.tagName == 'LINK' || !this.readyState || this.readyState == 'loaded' ) ScriptLoader.CheckQueue() ;}
ScriptLoader.CheckQueue = function() {
	if ( this.Queue.length > 0 ){ this.IsLoading = true ; var sScriptPath = this.Queue[0] ; var oTempArray = new Array() ;
		for ( i = 1 ; i < this.Queue.length ; i++ ) oTempArray[ i - 1 ] = this.Queue[ i ] ;
		this.Queue = oTempArray ; this.LoadFile( sScriptPath ) ;
	}else{
		this.IsLoading = false ;	if ( this.OnEmpty ) this.OnEmpty() ;
	}
}

ScriptLoader.LoadFile = function( filePath ) {
	var e ;
	if ( filePath.lastIndexOf( '.js' ) > 0 ){ e = document.createElement( "script" ) ; e.type	= "text/javascript" ;}else{ e = document.createElement( 'LINK' ) ; 	e.rel	= 'stylesheet' ;	e.type	= 'text/css' ;	}
	document.getElementsByTagName("head")[0].appendChild( e ) ; 
	if ( e.tagName == 'LINK' ){	if (BrowserInfo.isIE ) e.onload = ScriptLoader_OnLoad ; else ScriptLoader.CheckQueue() ; e.href = filePath ;}else{ e.onload = e.onreadystatechange = ScriptLoader_OnLoad ; e.src = filePath ;}
}

// 회원 가입
var popRegist = function(op_no) {
    var url = "/opuser/?control=Regist&op_no="+op_no+"&nocache="+Math.random();
    window.open(url, "opRegistPop", "width=588, height=550 , scrollbars=yes,resizable=no,status=0");
}

// 회원 불가
var popRegistDeny = function() {
	alert('홈페이지 템플릿엔 가입하실 수 없습니다.');
}

// 동보 쪽지
var popMymsg = function(op_no) {
    var url = "/opuser/?control=MyFacade&facade=MyMsg&op_no="+op_no+"&nocache="+Math.random();
    window.open(url, "opMyInfoPop", "width=588, height=550 , scrollbars=yes,resizable=no,status=0");
};

// 내정보
var popMyInfo = function(op_no) {
    var url = "/opuser/?control=MyFacade&facade=MyInfo&op_no="+op_no+"&nocache="+Math.random();
    window.open(url, "opMyInfoPop", "width=588, height=550 , scrollbars=yes,resizable=no,status=0");
};

// 숫자만 가능 여부 체크 
var Is_number	= function (value){
	var nStrLen, nPos;
	nStrLen = value.length;
	for(nPos = 0; nPos < nStrLen; nPos++){
		var nASCII = value.charCodeAt(nPos);
		if (nASCII > 57 || nASCII < 48) return false;	
	}
	return true;
};

// input check number
var check_number = function(obj) {
	var tmp_value = obj.value; 
	szValue = ''; 
	var chars;
	for(i=0;i<tmp_value.length;i++) { 
		chars  = tmp_value.substring(i,i+1); 
		if(chars == ','){
			szValue = szValue + chars; 
		}else if(chars < '0' || chars > '9') { 
			obj.value = szValue;
			return; 
		} else { 
			szValue = szValue + chars; 
		} 
	} 
}

// 이미지 크게 보기
var popup_thumnail = function(image_url){
	var szUrl = "/show_image.php?image_url="+image_url;
	window.open(szUrl, "showImage", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=100,height=100,topmargin=0,leftmargin=0");
}

// 플래쉬 보여주는 부분
var showFlash = function(szUrl, nWidth, nHeight){
	var szHtml = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width=" + nWidth + " height=" + nHeight + ">"
						+ "<param name=movie value='" + szUrl + "'>"
						+ "<param name=wmode value='transparent'>"
						+ "<param name=quality value=high>"
						+ "<param name=allowScriptAccess value='always'>"
						+ "<embed src='" + szUrl + "' quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' allowscriptaccess='always' wmode='transparent' menu='false' width=" + nWidth + " height=" + nHeight + ">"
						+ "</embed>"
						+ "</object>";
	document.write( szHtml );
}

// 플래쉬 보여주는 부분(innerHTML사용)
var showFlashArea = function(szUrl, nWidth, nHeight, szArea){
	var szHtml = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width=" + nWidth + " height=" + nHeight + ">"
						+ "<param name=movie value='" + szUrl + "'>"
						+ "<param name=wmode value='transparent'>"
						+ "<param name=quality value=high>"
						+ "<param name=allowScriptAccess value='always'>"
						+ "<embed src='" + szUrl + "' quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' wmode='transparent' menu='false'  allowscriptaccess='always' width=" + nWidth + " height=" + nHeight + ">"
						+ "</embed>"
						+ "</object>";
	$(szArea).innerHTML = szHtml;
}

// 플래쉬 보여주는 부분(flashvar 사용)
var showFlashAreaVar = function(szUrl, nWidth, nHeight, szArea, szVar){
	var szHtml = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width=" + nWidth + " height=" + nHeight + ">"
						+ "<param name=movie value='" + szUrl + "?" + szVar + "'>"
						+ "<param name=wmode value='transparent'>"
						+ "<param name='FlashVars' value='"+szVar +"'>"						
						+ "<param name=quality value=high>"
						+ "<param name=allowScriptAccess value='always'>"
						+ "<embed src='" + szUrl + "?" + szVar + "' quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' wmode='transparent' menu='false' allowscriptaccess='always' width=" + nWidth + " height=" + nHeight + ">"
						+ "</embed>"
						+ "</object>";
	$(szArea).innerHTML = szHtml;
}

// 쿠키정보
var getCookie = function(name){
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
      begin = dc.indexOf(prefix);
      if (begin != 0) return null;
    } else {
      begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
      end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
    
// 일반 쿠키
var getPlainCookie = function(name){
	var str = getCookie(name);
	if (str == null) return 0 ;
	var list = str.split('') ;
	var arrCookie = new Array();
	for(var i = 0; i < list.length; i++){
		var arrtmp = list[i].split('') ;
		arrCookie[arrtmp[0]] = arrtmp[1];
	}
	return arrCookie;
}

var findPosY = function(obj) {
    var curtop = 0;
    if (obj && obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    } else if (obj && obj.y) curtop += obj.y;
  
    return curtop;
}

var findPosX = function(obj) {
    var curleft = 0;
    if (obj && obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    } else if (obj && obj.x) curleft += obj.x;
    return curleft;
}

var clearDelimit = function(str,serchar){
	var reStr ="";
	var seStr =str;
	var i = 0; 
	for(i=0;i < seStr.length; i++){ 
		reStr += (seStr.charAt(i) != serchar ?seStr.charAt(i) : ''); 
	} 
	return reStr;
}

// 레이어 숨기기
var okCloseLayer = function(){
	try{Dialog.okCallback(); }catch(e){}
}

// 레이어 숨기기
var hideLayer = function(){
	try{Dialog.okCallback();  if(curHistoryLocation!='') ajax.arraypost(curHistoryLocation); }catch(e){}
}

var userFrame = function(szUrl,type){
	// logion check
	if(!getCookie("opTicket")){
		Dialog.message('로그인을 해주세요.');
		return;
	}
	Dialog.iframe({windowParameters: {className: "memberbox-container", url :szUrl, width:700, height:560}});
	if(type !=""){
		$("ohpytype").value = type;
	}
	var theform = document.loginForm;
	theform.target ="common_dialog_content";
	theform.action = szUrl;
	theform.submit();
}

var showBbsSelectBox = function(target, status){
	try{
	var activator = $(target);
	activator.style.display = "none";
	if(status == 1){
		return;
	}
	Event.observe(document, 'mouseup', function(){showBbsSelectBox(target, 1);}, false);
	activator.style.display = "";
	}catch(e){
	}
}

var showSelectBox = function(event, url, control, target, status){
	try{
		var activator = $(target);
		activator.style.display = "none";
		if(status == 1) return;
		var winWidth, winHeight, d=document;
		if (typeof window.innerWidth!='undefined') {
			winHeight = window.innerHeight;
		} else {
			if (d.documentElement && typeof d.documentElement.clientWidth!='undefined' && d.documentElement.clientWidth!=0) {
				winHeight = d.documentElement.clientHeight
			} else {
				if (d.body && typeof d.body.clientWidth!='undefined') {
					winHeight = d.body.clientHeight
				}
			}
		}
		winHeight = d.body.clientHeight;
		var realHeight = event.clientY + document.documentElement.scrollTop+ 100;
		if(winHeight < realHeight){
			Element.addClassName (activator,'selectbox-bottom');
		}
		Event.observe(document, 'mouseup', function(){showSelectBox(event, url, control, target, 1);}, false);
		ajax.get(url, control, target);
	}catch(e){
	}
}

// 고객 센터로 메일 보내기.
var popSendMail = function() {
	window.close();
	window.opener.location.href = "http://www.ohpy.com/?page_no=9"
//    var url = "/opuser/?control=Regist&branch=send_mail_form";
//    window.open(url, "opMail", "width=588, height=550 , scrollbars=yes,resizable=no,status=0");
}

// 아이디 비밀번호 찾기.
var popFindPw = function(op_no) {
    var url = "/opuser/?control=MyFacade&facade=Regist&branch=find_login_info_form&op_no=" + op_no;
    window.open(url, "opMail", "width=588, height=550 , scrollbars=yes,resizable=no,status=0");
}

// 주민등록번호 가입 확인(오피 만들기용)
ajax.residentCheck = function(array) {
    var res1 = $("resident_num1").value;
    var res2 = $("resident_num2").value;
    if(!Utils.validateFields({resident_num1:{empty:{name:'주민등록번호 앞자리를 입력해주세요.'}},resident_num2:{empty:{name:'주민등록번호 뒷자리를 입력해주세요.'}}})){
		return;
	}
	// 주민번호 유효성 검사
	if(!CheckResidentNum(res1, res2)){
		Dialog.message('잘못된 주민번호 형식입니다.');
		return;
	}
    var alnum="0123456789";
    for (i=0 ; i<res1.length; i++){
        if (alnum.indexOf(res1.substring(i,i+1))==-1){
			Dialog.message('주민등록번호는 숫자로 이루어져야합니다.');
    	    return;
        }
    }	
    for (i=0 ; i<res2.length; i++){
        if (alnum.indexOf(res2.substring(i,i+1))==-1){
			Dialog.message('주민등록번호는 숫자로 이루어져야합니다.');
    	    return;
        }
    }	    
	if(res1.length < 6) {
		Dialog.message('주민등록번호 뒷자리는 6자리입니다.');
	    return;	
	} else if(res2.length < 7) {
		Dialog.message('주민등록번호 뒷자리는 7자리입니다.');
	    return;	
	}
	ajax.post(array);
}

// SCRIPT 주민번호 유효성 검사
var CheckResidentNum = function(num1,num2){
	isCheckstatus = false;
	//2000 년생 체크
	b_Year = (num2.charAt(0) <= "2") ? "19" : "20";
	b_Year += num1.substr(0, 2);
	b_Month = num1.substr(2, 2) - 1;
	b_Date = num1.substr(4, 2);
	b_sum = new Date(b_Year, b_Month, b_Date);
	
	if ( b_sum.getYear() % 100 != num1.substr(0,2)
	|| b_sum.getMonth() != b_Month
	|| b_sum.getDate() != b_Date){ 
		return isCheckstatus;
	}
	total = 0;
	tmp = new Array(13);
	for(i=1; i<=6; i++){
		tmp[i] = num1.charAt(i-1);
	}
	for(i=7; i<=13; i++){
		tmp[i] = num2.charAt(i-7);
	}
	for(i=1; i<=12; i++) { 
		k = i + 1;
		if(k >= 10) k = k % 10 + 2;
		total = total + (tmp[i] * k);
	}
	last_num = (11- (total % 11)) % 10;
	if(last_num == tmp[13]) isCheckstatus = true;
	else isCheckstatus = false;
	return isCheckstatus;
}

//param obj, 글자수, 경고메세지 보여줄 여부[true, flase]
var character_cut		= function(id, max, isView){
	var tmpStr = $(id).value;
	character_byte( tmpStr, id, max, isView);
}

// 글자 바이트 검사
var character_byte	= function(obj,id, max, isView){
	var onechar;
	var count = 0;
	var tmpStr = new String(obj);
	var temp = tmpStr.length;
	for (var k=0; k<temp; k++){
		onechar = tmpStr.charAt(k);
		if (escape(onechar) =='%0D') { }
		else if (escape(onechar).length > 4){
			count += 2; 
		} else count++;
	}
	if(count > max){
		if(isView){
			alert('글자수가 초과되었습니다.');
		}
		var reserve = count- max;
		character_check(tmpStr,id, max, isView);
		return;
	}
}


//글자 검사
var character_check	= function(objStr,id, max, isView){
	var onechar;
    var tmpStr = new String(objStr);
    var temp = tmpStr.length;
	var count = 0;
    for(k=0;k<temp;k++){
		onechar = tmpStr.charAt(k);
		if(escape(onechar).length > 4) {
			count += 2;
		} else {
			// enter key 값이였을때
			if(escape(onechar)=='%0A') {
				if(BrowserInfo.isIE == false) {
					count++;
				} 
			} else {
				count++;	
			}
		}
		if(count> max){
			tmpStr = tmpStr.substring(0,k);
			break;
		}
	}
	$(id).value = tmpStr;
}

//레이어 위치를 센터로 옮기기.
var move_layer_center = function(layer_obj, layer_width,layer_height) {
	var left = (BrowserInfo.getClientWidth()  - layer_width)/2 + BrowserInfo.getScrollLeft();
	var top = (BrowserInfo.getClientHeight() - layer_height)/2 + BrowserInfo.getScrollTop();
	//레이어 우측 상단으로 이동.
	$(layer_obj).style.position ="absolute";
	$(layer_obj).style.left = left + "px";
	$(layer_obj).style.top = top+ "px";
}

var eventScroll = function(obj){
	var top = parseInt(obj.startY) + BrowserInfo.getScrollTop();
	new Effect.MoveBy( obj, (top), (obj.startX),{duration:0.9, mode: 'absolute'} );
}

var recentEleRequest = function(type) {
	var btn_id = "el" + type + "-btn";
	var oBtn_id = $("el" + type + "-btn");
	var oContent_plus = $(type + "_plus");

	if(Element.hasClassName(oBtn_id, btn_id + "-more")) {
		Element.removeClassName(oBtn_id, btn_id + "-more");
		Element.addClassName(oBtn_id, btn_id + "-less");	
		//Effect.toggle(oContent_plus, "blind");
		Element.show(oContent_plus);
		$(type + 'State').value = 1;
	} else {
		Element.removeClassName(oBtn_id, btn_id + "-less");
		Element.addClassName(oBtn_id, btn_id + "-more");	
		//Effect.toggle(oContent_plus, "blind");
		Element.hide(oContent_plus);
		$(type + 'State').value = 0;
	}
}

function actionObjSelectBox(obj,action) {
	selects = obj.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		if(action == "show") {
			selects[i].style.visibility = "visible";	
		} else if(action == "hide") {
			selects[i].style.visibility = "hidden";
		}
		
	}	
}

// select box를 보여주는 함수
function showSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// select box를 숨겨주는 함수
function hideSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

var TagManager = {
	stripLayer: function(oLayer) {
		if(oLayer == null) return;
		this.stripAnchor(oLayer);
		var oChilds = oLayer.getElementsByTagName("*");
		if(oChilds == null) return;
		for (var i=0; i<oChilds.length; i++) {
			this.stripAnchor(oChilds[i]);
		}
	},
	stripAnchor: function(oLayer) {
		if(oLayer.nodeType > 1) return;
		var sTagName = oLayer.tagName.toUpperCase();
		if(!['A','SPAN','IMG','DIV','FORM','LI', 'AREA'].include(sTagName)) {
			return;
		}
		if(sTagName == "A" || sTagName == "AREA") {
			oLayer.setAttribute("href", "#//");
			oLayer.removeAttribute("target");
		} else if(sTagName == "FORM") {
			oLayer.onsubmit = function() { return false; };
		}
		oLayer.onclick = null;
		oLayer.onmouseover = null;
		oLayer.onmouseout = null;
	}
}

// hex 를 rgb 값으로 변환하는 함수 - 상세 꾸미기, 영역별 설정, 색상 변경시 쓰임.
var hex2rgb2 = function(hex)	{
	var hex= hex.replace('#','');
	var szCheck = /[a-f\d]$/i;

	if((hex.length == 3 || hex.length == 6) && szCheck.test(hex)){
		if(hex.length == 3){
			hex = hex.match(/./g);
			hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
		}
		hex = hex.match(/../g);
		return{
			r : Number("0x"+hex[0]),
			g : Number("0x"+hex[1]),
			b : Number("0x"+hex[2])
		}
	}
}

// iframe resize
// for FF
var resizeIframe = function(subWin){ 
    var frameObj = document.getElementById(subWin);
    var subDoc = frameObj.contentWindow.document.body;
    
    //var frameHeight = subDoc.offsetHeight;
    //var frameWidth = subDoc.offsetWidth;
    var frameHeight = subDoc.scrollHeight;
    var frameWidth = document.getElementById('opm').offsetWidth;
    
    frameObj.height = frameHeight;
    frameObj.width = frameWidth;
} 

var GnbSub  = {
	gnbList: [],
	opNo:0,
	szHtml : "",
	gnbNo:0,
	
	initialize: function(){
	},
	getSubList : function(params){
		if(typeof params['ele_gnb_no'] != 'undefined') {
			this.gnbNo = params['ele_gnb_no'];
		} else {
			for(var i=0;i<this.gnbList.length;i++){
				if(this.gnbList[i].bbs_no == params['bbs_no'] && this.gnbList[i].menu_type == params['gnb_type']){		
					this.gnbNo = this.gnbList[i].ele_gnb_no;
					break;
				}	
			}
		}

		if(this.gnbList.length != 0 && this.gnbNo != 0){
			var gnbHtml = '';
			var subHtml = '';
			
			for(var i=0;i<this.gnbList.length;i++){
				if(this.gnbList[i].ele_gnb_no == this.gnbNo){
					if(this.gnbList[i].parent_ele_gnb_no != 0){
						this.gnbNo = this.gnbList[i].parent_ele_gnb_no;
						break;
					}
				}
			}

			//1단 메뉴
			var countDepth1 = 1;	
			var szDepth1  = '';
			for(var i=0;i<this.gnbList.length;i++){
				if(this.gnbList[i].ele_gnb_no == this.gnbNo){
					szDepth1 += "<span class='item'>"+this.getGnbLinkHtml(this.gnbList[i])+"</span>";
					countDepth1++;
				}
			}
			
			//2단 메뉴
			var countDepth2 = 1;			
			var szDepth2  = '<ul class="subnavi">';
			for(var i=0;i<this.gnbList.length;i++){
				if(this.gnbList[i].parent_ele_gnb_no == this.gnbNo){	
					szDepth2 += "<li class='submenu submenu"+countDepth2+"'>";
					szDepth2 += "<span class='subitem'>"+this.getGnbLinkHtml(this.gnbList[i])+"</span>";
					szDepth2 += "</li>";
					countDepth2++;
				}
			}
			szDepth2  += '</ul>';	
			if(countDepth2 == 1) { szDepth2 = ''; }
			
			szHtml = "<ul class='navi'>";
			szHtml +="<li class='menu menu"+this.gnbNo+"'>";
			szHtml += (szDepth1 +szDepth2);
			szHtml +="</li></ul>";

			this.makeHtml(szHtml);
			return true;
		} else {
			return false;
		}
	},
	
	getGnbLinkHtml : function(gnbList){
		var subHtml = '';
		if(gnbList.bbs_no != 0){
			if(gnbList.menu_type == "" || gnbList.menu_type == "BBS"){
				subHtml += '<a href="/'+gnbList.bbs_no+'/0" onclick="ajax._send({url : \'/opbbs/\', query : \'control=List&op_no='+this.opNo+'&bbs_no='+gnbList.bbs_no+'\', div: \'opm\', form:\'\', method:\'get\'}); return false;" style="cursor:pointer;" >' +gnbList.menu_name+'</a>';						
			}else if(gnbList.menu_type == "HTML"){
				subHtml += '<a href="/page/'+gnbList.bbs_no+'" onclick="ajax._send({url: \'/page/'+gnbList.bbs_no+'\' , query: \'\', div : \'opm\', method:\'get\'}); return false;" style="cursor:pointer;" >'+gnbList.menu_name+'</a>';
			}
		} else{
			subHtml += '<a href="#//" style="cursor:default;" >'+gnbList.menu_name+'</a>';
		}
		return subHtml;
	},
	
	makeHtml : function(szHtml){
		Element.update('elsnb', '');
		var contentDiv  = document.createElement("div");
		Element.addClassName(contentDiv, 'elsnb-content');
		contentDiv.innerHTML = szHtml;
		$('elsnb').appendChild(contentDiv);	
		Element.show('elsnb');		
	}
}

Object.extend(ajax, {
	_setSubList : function(fields){
		try {
			GnbSub.getSubList(fields['query'].toQueryParams());
		} catch(e) {
		}
		
		if(fields['url'] != ''){
			this._send(fields);
		}
	},
	_setFlashSubList : function(fields){
		if(fields['url'] != ''){
			this._send(fields);
		}
	}
});

// 스킨 관련 함수 정의
var opskin = {};
Object.extend(opskin, {
	skinStore:function(obj){var url = obj.url; url = url+"?"+obj.branch; window.open(url, "skinStore", "width=350, height=228 , scrollbars=no,resizable=no,status=0");},
	overPreview : function(obj,szClassName){	var objElement = Element.getDescendantByClassName(obj,szClassName); Element.show(objElement);},
	outPreview : function(obj,szClassName){ var objElement = Element.getDescendantByClassName(obj,szClassName); Element.hide(objElement);	}
});

var setMailHost = function() {
    alert(1);
	return;

}  