// 브라우저 정보
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;

}  //-----------------------------------------------------------------------------------
//	Lightbox v2.02
//	by Lokesh Dhakar - http://www.huddletogether.com 
//	For more information on this script, visit:
//	http://huddletogether.com/projects/lightbox2/
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//	
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.org), Thomas Fuchs(mir.aculo.us), and others.
// -----------------------------------------------------------------------------------


Object.extend(Element, {
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setAlt: function(element,alt) {
    	element = $(element);
    	element.alt = alt; 
	},	
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

//
//	Lightbox Class Declaration
//- initialize()
//- reinitialize()
//- setElementOverlay()
//- setElementLightbox()
//- setElementOuterImageContainer()
//- setElementImageDataContainer()
//- setClickEvent()

//- start()
//- resizeImageContainer()
//- showImage()
//- showImageDataContainer()
//- updateScrollImage()
//- updateImage()
//- percentageImage()
//- showImageByExpand()
//- resizeImage()
//- originalImage()
//- showExpandImage()
//- hideExpandImage()
//- end()
//

//
//	Global Variables
//
var imageArray = new Array;
var activeImage;

var Lightbox = Class.create();
       
Lightbox.prototype = {
	loadingImage : "lightbox-loading",
	closeImage : "lightbox-btn-close",
	prevImage : "lightbox-btn-prev",
	nextImage : "lightbox-btn-next",
	expandImage : "lightbox-btn-expand",
	shrinkImage : "lightbox-btn-shrink",
	//	expandImage : "http://img.ohpy.com/opimg/common/lightbox/img/expand.gif",
	//shrinkImage : "http://img.ohpy.com/opimg/common/lightbox/img/shrink.gif",
	
	
	resizeSpeed : 10,
	resizeDuration : (11 - this.resizeSpeed) * 0.15,
	borderSize : 10,
	outBorderSize : 34,
	
	widthMargin : 60,
	heightMargin : 150,

	isExtendImage : false,
	isMouseOver : false,
	
	arrayPageSize : [],	
	
	initialize: function() {	
		this.setClickEvent();
		var objBody = document.getElementsByTagName("body").item(0);
		objBody.appendChild(this.setElementOverlay());
		objBody.appendChild(this.setElementLightbox());
	},

	reinitialize: function() {
		this.setClickEvent();
	},
	
	// setElementOverlay html 
	setElementOverlay : function() {
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');
		objOverlay.style.display = 'none';
		objOverlay.onclick = function() { myLightbox.end(); return false; }
		return objOverlay;
	},
	
	// setElementLightbox Html
	setElementLightbox : function() {
		var objPrevLink = document.createElement("div");
		objPrevLink.setAttribute('id', this.prevImage);
		objPrevLink.setAttribute('title',"이전");
		with (objPrevLink.style) {position = 'absolute'; left = 0+'px';}
		objPrevLink.onmouseover = function() {myLightbox.showImageButton(); return false; }
		objPrevLink.style.cursor = "pointer";
		
		var objNextLink = document.createElement("div");
		objNextLink.setAttribute('id', this.nextImage);
		objNextLink.setAttribute('title',"다음");
		with (objNextLink.style) {position = 'absolute';	right = 0+'px';}
		objNextLink.onmouseover = function() {myLightbox.showImageButton(); return false; }
		objNextLink.style.cursor = "pointer";
		
		var objNaviBtnContainer = document.createElement("div");
		objNaviBtnContainer.setAttribute('id','navi-btn-container');
		objNaviBtnContainer.onmouseover = function() {myLightbox.showImageButton();}
		objNaviBtnContainer.onmouseout = function() {myLightbox.hideImageButton();}		
		objNaviBtnContainer.appendChild(this.setElementOuterImageContainer());
		objNaviBtnContainer.appendChild(this.setElementImageDataContainer());
		objNaviBtnContainer.appendChild(objPrevLink);
		objNaviBtnContainer.appendChild(objNextLink);
		
		var objLightbox = document.createElement("div");
		objLightbox.setAttribute('id','lightbox');
		objLightbox.style.display = 'none';
		objLightbox.appendChild(objNaviBtnContainer);
		return objLightbox;
	},
	
	// setElementOuterImageContainer Html
	setElementOuterImageContainer : function() {
		var objLightboxImage = document.createElement("img");
		objLightboxImage.setAttribute('id','lightboxImage');
		objLightboxImage.setAttribute('src','about:blank');
		objLightboxImage.setAttribute('alt','image');
		objLightboxImage.onclick = function() { myLightbox.end(); return false; }
		objLightboxImage.onmouseover = function() { myLightbox.isMouseOver = true; myLightbox.showExpandImage();}
		objLightboxImage.onmouseout = function() {myLightbox.isMouseOver = false; myLightbox.showExpandImage();}
		objLightboxImage.style.cursor = "pointer";
		
		var objExpandImage = document.createElement("div");
		objExpandImage.setAttribute('id','lightbox-expand');
		objExpandImage.className = 'lightmax';
		objExpandImage.onclick = function() {myLightbox.showImageByExpand(); }
		objExpandImage.onmouseover = function() {myLightbox.isMouseOver = true;  myLightbox.showExpandImage(); return false; }

		var objImageContainer = document.createElement("div");
		objImageContainer.setAttribute('id','imageContainer');

		var objLoading = document.createElement("div");
		objLoading.setAttribute('id',this.loadingImage);
		
		objImageContainer.appendChild(objLoading);
		objImageContainer.appendChild(objLightboxImage);		
		objImageContainer.appendChild(objExpandImage);
		
		var objOuterImageContainer = document.createElement("div");
		objOuterImageContainer.setAttribute('id','outerImageContainer');
		objOuterImageContainer.style.display = 'none';
		objOuterImageContainer.appendChild(objImageContainer);		
		return objOuterImageContainer;
	},
	
	// setElementImageDataContainer
	setElementImageDataContainer : function() {
		var objBottomNav = document.createElement("div");
		objBottomNav.setAttribute('id',this.closeImage);

		var objBottomNavCloseLink = document.createElement("a");
		objBottomNavCloseLink.setAttribute('id','bottomNavClose');
		objBottomNavCloseLink.setAttribute('href','#//');
		objBottomNavCloseLink.onclick = function() { myLightbox.end(); return false; }
		objBottomNav.appendChild(objBottomNavCloseLink);

		var objImageDataContainer = document.createElement("div");
		objImageDataContainer.setAttribute('id','imageDataContainer');
		objImageDataContainer.className = 'clearfix';
		objImageDataContainer.appendChild(objBottomNav);		
		return objImageDataContainer;
	},
	
	//	ready()
	setClickEvent : function() {
		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			var relAttribute = String(anchor.getAttribute('rel'));
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
				anchor.onclick = function () {myLightbox.start(this); return false;}
			}
		}
	},
				
	//	start()
	start: function(imageLink) {
		this.isMouseOver = false;
	    var imgHref = imageLink.getAttribute('href').replace('#','%');
		hideSelectBoxes();

		if(BrowserInfo.isIE6){
			imgHref = escape(imgHref);
			imgHref = imgHref.replace(/%3A/,':');
		}
		
		this.getPageSize();
    	Element.setStyle($('overlay'), {width : this.arrayPageSize[0] +"px", height : this.arrayPageSize[1] +"px"})
    	Element.show('overlay');
		Element.show('navi-btn-container');
		Element.setStyle($('lightbox'), {top: (this.arrayPageSize[3] - 500)/2  + this.arrayPageSize[4]});
		Element.show('lightbox');
		Element.setStyle($('outerImageContainer'), {width : 250 +"px", height : 270 +"px"});
		Element.show('outerImageContainer');

		Element.show('lightbox-loading');
		Element.hide('lightbox-expand');
		Element.hide('lightboxImage');
		Element.hide('imageDataContainer');
		Element.hide('lightbox-btn-prev');
		Element.hide('lightbox-btn-next');
		
		imageArray = [];
		imageNum = 0;
		
		if((imageLink.getAttribute('rel') == 'lightbox')){
			imageArray.push(new Array(imgHref, imageLink.getAttribute('title')));
		} else {
			var anchors = document.getElementsByTagName(imageLink.tagName);
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];
				var anchorimgHref = anchor.getAttribute('href')
				if (anchorimgHref && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
					if(BrowserInfo.isIE6){
						anchorimgHref = escape(anchorimgHref);
						anchorimgHref = anchorimgHref.replace(/%3A/,':');
					}
					imageArray.push(new Array(anchorimgHref, anchor.getAttribute('title')));
				}
			}
			 for(i = 0; i < imageArray.length; i++){
		        for(j = imageArray.length-1; j>i; j--){        
		            if(imageArray[i][0] == imageArray[j][0]){
		                imageArray.splice(j,1);
		            }
		        }
		    }
			while(imageArray[imageNum][0] != imgHref) { 
				imageNum++;
			}
		}

		this.changeImage(imageNum);

		this.eventResize = this.updateImage.bindAsEventListener(this);
		Event.observe(window, "resize",this.eventResize, false);
		this.eventScroll = this.updateScrollImage.bindAsEventListener(this);
		Event.observe(window, "scroll",this.eventScroll, false);
	},

	changeImage: function(imageNum) {
		this.isMouseOver = false;
		this.isExtendImage = false;
		Element.show('lightbox-loading');
		Element.hide('lightboxImage');
		this.hideImageButton();
		Element.hide('imageDataContainer');
	
		activeImage = imageNum;

		imgPreloader = new Image();
		myLightbox.imgPreloader = new Image();

		imgPreloader.onload=function(){
			Element.hide('lightbox-loading');
			$('lightboxImage').alt = '';
			$('lightboxImage').src = imageArray[activeImage][0];
			myLightbox.imgPreloader = imgPreloader;
			myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
			imgPreloader.onload=function(){};
		}
		imgPreloader.src = imageArray[activeImage][0];
	},

	resizeImageContainer: function(imgWidth, imgHeight) {
		Element.setStyle($('lightbox'), {top : ((this.arrayPageSize[3] - this.imgPreloader.height)/2  + this.arrayPageSize[4])+"px"});	
		Element.setStyle($('outerImageContainer'), {width : imgWidth + (this.borderSize * 2) + "px", height : imgHeight + (this.borderSize * 2) + "px"});
		Element.setStyle($('navi-btn-container'), {width : ($('outerImageContainer').offsetWidth + (this.outBorderSize * 2) + 5) + "px", height : ($('outerImageContainer').offsetHeight) + "px"});
		this.showImage();
	},
	
	showImage: function(imageNum){
		Element.setStyle($('lightboxImage'), {top : 500 + "px"})
		if(this.imgPreloader.width > this.arrayPageSize[2] || this.imgPreloader.height > this.arrayPageSize[3]) {
			$('lightbox-expand').className = 'lightmin';
			this.showImageByExpand();
			this.updateImage();
		} else {
			Element.setStyle($('lightboxImage'), {width : this.imgPreloader.width + "px", height : this.imgPreloader.width + "px"})
			Element.setWidth('lightboxImage', this.imgPreloader.width);
			Element.setHeight('lightboxImage', this.imgPreloader.height);
		}	
				
		new Effect.Appear('lightboxImage', { duration: 0.5, queue: 'end', afterFinish: function(){	myLightbox.showImageDataContainer(); } });
		this.preloadNeighborImages();
	},
	
	showImageDataContainer: function() {	
		Element.setWidth( 'imageDataContainer',  $('lightboxImage').offsetWidth + (this.borderSize * 2));

		new Effect.Parallel(
			[ new Effect.SlideDown( 'imageDataContainer', { sync: true, duration: this.resizeDuration + 0.25, from: 0.0, to: 1.0 }), 
			  new Effect.Appear('imageDataContainer', { sync: true, duration: 1.0 }) ], 	
			  { duration: 0.65} );
	},
	
	showImageButton: function() {
		if(activeImage != 0){
			if($('lightboxImage').offsetHeight) {
				Element.setTop('lightbox-btn-prev', $('lightboxImage').offsetHeight/2 );
				Element.show('lightbox-btn-prev');
			}
			$('lightbox-btn-prev').onclick = function() {
				myLightbox.changeImage(activeImage - 1); return false;
			}
		}
		if(activeImage != (imageArray.length - 1)){
			if($('lightboxImage').offsetHeight) {
				Element.setTop('lightbox-btn-next', $('lightboxImage').offsetHeight/2 );
				Element.show('lightbox-btn-next');
			}
			$('lightbox-btn-next').onclick = function() {
				myLightbox.changeImage(activeImage + 1); return false;
			}
		}
	},
	
	hideImageButton: function() {
		Element.hide('lightbox-btn-prev');
		Element.hide('lightbox-btn-next');
	},
	
	preloadNeighborImages: function(){
		if((imageArray.length - 1) > activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = imageArray[activeImage + 1][0];
		}
		if(activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = imageArray[activeImage - 1][0];
		}
	
	},
		
	updateScrollImage : function(){
		if(($('lightbox-expand').className != 'lightmin') || !(this.imgPreloader.width > this.arrayPageSize[2] || this.imgPreloader.height > this.arrayPageSize[3])) {
			this.updateImage();
		}
	},
	
	updateImage : function() {
		this.getPageSize();
		Element.setWidth('overlay', this.arrayPageSize[0]);
		Element.setHeight('overlay', this.arrayPageSize[1]);
		
		if(this.imgPreloader.width != 0 && this.imgPreloader.height != 0) {
			if(this.imgPreloader.width > this.arrayPageSize[2] || this.imgPreloader.height > this.arrayPageSize[3]){
				aImgSize = this.percentageImage(this.arrayPageSize[2], this.arrayPageSize[3]);
				this.resizeImage(aImgSize[0], aImgSize[1], this.arrayPageSize[3], this.arrayPageSize[4]);
			}else{
				this.originalImage();
			}
		}
	},

	percentageImage : function(windowWidth, windowHeight) {
		if ( (this.imgPreloader.width / (windowWidth - this.widthMargin)) > (this.imgPreloader.height /(windowHeight - this.heightMargin))){
			nWidth = windowWidth - this.widthMargin;
			nHeight = Math.round(this.imgPreloader.height * ((windowWidth - this.heightMargin) / this.imgPreloader.width));
		}else{
			nWidth = Math.round(this.imgPreloader.width * ((windowHeight - this.heightMargin) / this.imgPreloader.height));
			nHeight = windowHeight - this.heightMargin;
		}
		aImgSize = new Array(nWidth, nHeight)
		
		return aImgSize;		
	},
	
	showImageByExpand: function() {
		if($('lightbox-expand').className == 'lightmax'){
			this.originalImage();
		}else {
			aImgSize = this.percentageImage(this.arrayPageSize[2], this.arrayPageSize[3]);
			this.resizeImage(aImgSize[0], aImgSize[1], this.arrayPageSize[3], this.arrayPageSize[4]);
		}
		this.showExpandImage();
		$('lightbox-expand').className = ($('lightbox-expand').className == 'lightmax') ? 'lightmin' : 'lightmax';		
		(this.isExtendImage == true)? this.isExtendImage = false : this.isExtendImage = true;
	},	
	
	resizeImage : function(nWidth, nHeight, clientHeight, scrollTop) {
		Element.setTop('lightbox', (clientHeight - nHeight)/2  + scrollTop);
		
		nWidth = nWidth - this.outBorderSize;
		nHeight = nHeight - this.outBorderSize;

		Element.setWidth('lightboxImage', nWidth);
		Element.setHeight('lightboxImage', nHeight);
		Element.setWidth( 'outerImageContainer', nWidth + (this.borderSize * 2));
		Element.setHeight( 'outerImageContainer', nHeight  + (this.borderSize * 2));		
		Element.setWidth( 'navi-btn-container',  $('outerImageContainer').offsetWidth + (this.outBorderSize * 2) + 5);
		Element.setHeight( 'navi-btn-container',  $('outerImageContainer').offsetHeight);
		Element.setWidth( 'imageDataContainer', $('lightboxImage').offsetWidth + (this.borderSize * 2));
	},
	
	originalImage : function() {
		Element.setTop('lightbox', (this.imgPreloader.height > this.arrayPageSize[4]) ? this.arrayPageSize[4] + 20 : (this.arrayPageSize[3] - this.imgPreloader.height)/2  + this.arrayPageSize[4]);
		Element.setWidth('overlay', (this.arrayPageSize[0]< this.imgPreloader.width) ? this.arrayPageSize[0]+this.imgPreloader.width : this.arrayPageSize[0]);
		Element.setHeight('overlay', this.arrayPageSize[1]);
		Element.setWidth('lightboxImage', this.imgPreloader.width);
		Element.setHeight('lightboxImage', this.imgPreloader.height);
		Element.setWidth( 'outerImageContainer', this.imgPreloader.width + (this.borderSize * 2));
		Element.setHeight( 'outerImageContainer', this.imgPreloader.height + (this.borderSize * 2));	
		Element.setWidth( 'navi-btn-container',  $('outerImageContainer').offsetWidth + (this.outBorderSize * 2) + 5);
		Element.setHeight( 'navi-btn-container',  $('outerImageContainer').offsetHeight);					
		Element.setWidth( 'imageDataContainer', this.imgPreloader.width + (this.borderSize * 2));
	},
	showExpandImage: function(){
		if(this.isMouseOver && (this.imgPreloader.width > this.arrayPageSize[2] || this.imgPreloader.height > this.arrayPageSize[3])) {
			Element.show('lightbox-expand');
		}else{
			Element.hide('lightbox-expand');
		}	
	},
	//	end()
	end: function() {
		$('lightbox').oncontextmenu = null; 
		$('lightbox').onselectstart = null; 
		$('lightbox').ondragstart = null;
		$('lightbox').onkeydown = null;	

		Element.hide('lightbox-expand');
		Element.hide('lightbox-btn-prev');
		Element.hide('lightbox-btn-next');
		Element.hide('lightbox');
		Element.hide('lightbox-loading');
		Element.hide('overlay');
		
		showSelectBoxes();
		Event.stopObserving(window, "resize", this.eventResize);
		Event.stopObserving(window, "scroll", this.eventScroll);
		if(this.isExtendImage == true) this.isExtendImage = false;
		
	}, 	
	getPageSize : function(){
		pageWidth = BrowserInfo.getDocumentWidth();
		pageHeight = BrowserInfo.getDocumentHeight();
		windowWidth = BrowserInfo.getClientWidth();
		windowHeight = BrowserInfo.getClientHeight();
		scrollTop = BrowserInfo.getScrollTop();
		this.arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight, scrollTop) 
	}
}

function initLightbox() { myLightbox = new Lightbox(); }
Event.observe(window, 'load', initLightbox, false);// Flash Player Version Detection - Rev 1.6
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
// 저작권은 Adobe Macromedia 사에 있습니다.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion(){
	var version;
	var axo;
	var e;
	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	if (!version){
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			// default to the first public version
			version = "WIN 6,0,21,0";
			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";
			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version){
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version){
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}
	if (!version){
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision){
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext){
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs, divFlashIds, isInnerHTML){
    var str = '';
    if (isIE && isWin && !isOpera)
    {
  		str += '<object ';
  		for (var i in objAttrs)
  			str += i + '="' + objAttrs[i] + '" ';
  		for (var i in params)
  			str += '><param name="' + i + '" value="' + params[i] + '" /> ';
  		str += '></object>';
    } else {
  		str += '<embed ';
  		for (var i in embedAttrs){
  			str += i + '="' + embedAttrs[i] + '" ';
  		}
  		str += '> </embed>';
    }
    if(isInnerHTML == true) {
		var szFlashId = divFlashIds['flash_div_id'];
//alert(szFlashId);		
    	var obj = document.getElementById(szFlashId);
		if(obj) {
			obj.innerHTML = str;
		}
    } else {
    	document.write(str);
    }
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs, ret.divFlashIds, false);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  ret.divFlashIds = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();
    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "id":
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      case "flash_div_id":
        ret.divFlashIds[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

function AC_FL_RunContent_innerHTML(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
    
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs, ret.divFlashIds, true);
}

// Upload Logic

// script.aculo.us effects.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
String.prototype.parseColor = function() {  var color = '#'; if(this.slice(0,4) == 'rgb(') { var cols = this.slice(4,this.length-1).split(','); var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); } else { if(this.slice(0,1) == '#') { if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); if(this.length==7) color = this.toLowerCase(); }} return(color.length==7 ? color : (arguments[0] || this)); }
Element.collectTextNodes = function(element) { return $A($(element).childNodes).collect( function(node) { return (node.nodeType==3 ? node.nodeValue : (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); }).flatten().join('');}
Element.collectTextNodesIgnoreClass = function(element, className) { return $A($(element).childNodes).collect( function(node) { return (node.nodeType==3 ? node.nodeValue : ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? Element.collectTextNodesIgnoreClass(node, className) : ''));}).flatten().join('');}
Element.setContentZoom = function(element, percent) { element = $(element);  Element.setStyle(element, {fontSize: (percent/100) + 'em'}); if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); }
Element.getOpacity = function(element){ var opacity; if (opacity = Element.getStyle(element, 'opacity')) return parseFloat(opacity); if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/)) if(opacity[1]) return parseFloat(opacity[1]) / 100; return 1.0; }
Element.setOpacity = function(element, value){ element= $(element); if (value == 1){ Element.setStyle(element, { opacity: (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0 }); if(/MSIE/.test(navigator.userAgent) && !window.opera) Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')}); } else { if(value < 0.00001) value = 0; Element.setStyle(element, {opacity: value}); if(/MSIE/.test(navigator.userAgent) && !window.opera) Element.setStyle(element, { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') + 'alpha(opacity='+value*100+')' }); }}  
Element.getInlineOpacity = function(element){  return $(element).style.opacity || ''; }  
Element.childrenWithClassName = function(element, className, findFirst) { var classNameRegExp = new RegExp("(^|\\s)" + className + "(\\s|$)"); var results = $A($(element).getElementsByTagName('*'))[findFirst ? 'detect' : 'select']( function(c) { return (c.className && c.className.match(classNameRegExp)); }); if(!results) results = []; return results; }
Element.forceRerendering = function(element) { try { element = $(element); var n = document.createTextNode(' '); element.appendChild(n); element.removeChild(n); } catch(e) { } };
Array.prototype.call = function() { var args = arguments; this.each(function(f){ f.apply(this, args) }); }
var Effect = { _elementDoesNotExistError: { name: 'ElementDoesNotExistError', message: 'The specified DOM element does not exist, but is required for this effect to operate' }, tagifyText: function(element) { if(typeof Builder == 'undefined') throw("Effect.tagifyText requires including script.aculo.us' builder.js library"); var tagifyStyle = 'position:relative'; if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1'; element = $(element); $A(element.childNodes).each( function(child) { if(child.nodeType==3) { child.nodeValue.toArray().each( function(character) { element.insertBefore( Builder.node('span',{style: tagifyStyle}, character == ' ' ? String.fromCharCode(160) : character), child); }); Element.remove(child); } }); }, multiple: function(element, effect) { var elements; if(((typeof element == 'object') || (typeof element == 'function')) && (element.length)) elements = element; else elements = $(element).childNodes; var options = Object.extend({ speed: 0.1, delay: 0.0 }, arguments[2] || {}); var masterDelay = options.delay; $A(elements).each( function(element, index) { new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); }); }, PAIRS: { 'slide':  ['SlideDown','SlideUp'], 'blind':  ['BlindDown','BlindUp'], 'appear': ['Appear','Fade'] }, toggle: function(element, effect) { element = $(element); effect = (effect || 'appear').toLowerCase(); var options = Object.extend({ queue: { position:'end', scope:(element.id || 'global'), limit: 1 } }, arguments[2] || {}); Effect[element.visible() ? Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options); } };
var Effect2 = Effect; Effect.Transitions = {}; Effect.Transitions.linear = Prototype.K; Effect.Transitions.sinoidal = function(pos) { return (-Math.cos(pos*Math.PI)/2) + 0.5; }; Effect.Transitions.reverse  = function(pos) { return 1-pos; }; Effect.Transitions.flicker = function(pos) { return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4; }; Effect.Transitions.wobble = function(pos) { return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5; }; Effect.Transitions.pulse = function(pos) { return (Math.floor(pos*10) % 2 == 0 ?  (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10))); }; Effect.Transitions.none = function(pos) { return 0; }; Effect.Transitions.full = function(pos) { return 1; };
Effect.ScopedQueue = Class.create(); Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), { initialize: function() { this.effects  = []; this.interval = null; }, _each: function(iterator) { this.effects._each(iterator); }, add: function(effect) { var timestamp = new Date().getTime();  var position = (typeof effect.options.queue == 'string') ? effect.options.queue : effect.options.queue.position; switch(position) { case 'front': this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { e.startOn  += effect.finishOn; e.finishOn += effect.finishOn; }); break; case 'end': timestamp = this.effects.pluck('finishOn').max() || timestamp; break; } effect.startOn  += timestamp; effect.finishOn += timestamp; if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) this.effects.push(effect); if(!this.interval) this.interval = setInterval(this.loop.bind(this), 40); }, remove: function(effect) { this.effects = this.effects.reject(function(e) { return e==effect }); if(this.effects.length == 0) { clearInterval(this.interval); this.interval = null; }}, loop: function() { var timePos = new Date().getTime(); this.effects.invoke('loop', timePos); } });
Effect.Queues = { instances: $H(), get: function(queueName) { if(typeof queueName != 'string') return queueName; if(!this.instances[queueName]) this.instances[queueName] = new Effect.ScopedQueue(); return this.instances[queueName];}}
Effect.Queue = Effect.Queues.get('global');
Effect.DefaultOptions = { transition: Effect.Transitions.sinoidal, duration:1.0,fps:25.0,  sync:false,  from:0.0,to:1.0, delay:0.0, queue:'parallel' }
Effect.Base = function() {}; Effect.Base.prototype = { position: null, start: function(options) { this.options      = Object.extend(Object.extend({},Effect.DefaultOptions), options || {}); this.currentFrame = 0; this.state        = 'idle'; this.startOn      = this.options.delay*1000; this.finishOn     = this.startOn + (this.options.duration*1000); this.event('beforeStart'); if(!this.options.sync) Effect.Queues.get(typeof this.options.queue == 'string' ?  'global' : this.options.queue.scope).add(this); }, loop: function(timePos) { if(timePos >= this.startOn) { if(timePos >= this.finishOn) { this.render(1.0); this.cancel(); this.event('beforeFinish'); if(this.finish) this.finish();  this.event('afterFinish'); return;   } var pos   = (timePos - this.startOn) / (this.finishOn - this.startOn); var frame = Math.round(pos * this.options.fps * this.options.duration); if(frame > this.currentFrame) { this.render(pos); this.currentFrame = frame; } } }, render: function(pos) { if(this.state == 'idle') { this.state = 'running'; this.event('beforeSetup'); if(this.setup) this.setup(); this.event('afterSetup'); } if(this.state == 'running') { if(this.options.transition) pos = this.options.transition(pos); pos *= (this.options.to-this.options.from); pos += this.options.from; this.position = pos; this.event('beforeUpdate'); if(this.update) this.update(pos); this.event('afterUpdate'); }}, cancel: function() { if(!this.options.sync) Effect.Queues.get(typeof this.options.queue == 'string' ?  'global' : this.options.queue.scope).remove(this); this.state = 'finished'; }, event: function(eventName) { if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); if(this.options[eventName]) this.options[eventName](this); }, inspect: function() { return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>'; } }
Effect.Parallel = Class.create(); Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), { initialize: function(effects) { this.effects = effects || []; this.start(arguments[1]); }, update: function(position) { this.effects.invoke('render', position);}, finish: function(position) { this.effects.each( function(effect) { effect.render(1.0); effect.cancel(); effect.event('beforeFinish'); if(effect.finish) effect.finish(position); effect.event('afterFinish'); }); } });
Effect.Opacity = Class.create(); Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), { initialize: function(element) { this.element = $(element); if(!this.element) throw(Effect._elementDoesNotExistError); if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout)) this.element.setStyle({zoom: 1}); var options = Object.extend({ from: this.element.getOpacity() || 0.0, to:   1.0 }, arguments[1] || {}); this.start(options); }, update: function(position) { this.element.setOpacity(position); } });
Effect.Move = Class.create(); Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), { initialize: function(element) { this.element = $(element); if(!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ x:    0, y:    0, mode: 'relative' }, arguments[1] || {}); this.start(options); }, setup: function() {  this.element.makePositioned(); this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); this.originalTop  = parseFloat(this.element.getStyle('top')  || '0'); if(this.options.mode == 'absolute') {  this.options.x = this.options.x - this.originalLeft; this.options.y = this.options.y - this.originalTop; } }, update: function(position) { this.element.setStyle({ left: Math.round(this.options.x  * position + this.originalLeft) + 'px', top:  Math.round(this.options.y  * position + this.originalTop)  + 'px' }); } });
Effect.MoveBy = function(element, toTop, toLeft) { return new Effect.Move(element,  Object.extend({ x: toLeft, y: toTop }, arguments[3] || {})); };
Effect.Scale = Class.create(); Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {initialize: function(element, percent) { this.element = $(element); if(!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ scaleX: true, scaleY: true, scaleContent: true, scaleFromCenter: false, scaleMode: 'box', scaleFrom: 100.0, scaleTo:   percent }, arguments[2] || {}); this.start(options); }, setup: function() { this.restoreAfterFinish = this.options.restoreAfterFinish || false; this.elementPositioning = this.element.getStyle('position'); this.originalStyle = {}; ['top','left','width','height','fontSize'].each( function(k) { this.originalStyle[k] = this.element.style[k]; }.bind(this)); this.originalTop  = this.element.offsetTop; this.originalLeft = this.element.offsetLeft; var fontSize = this.element.getStyle('font-size') || '100%'; ['em','px','%','pt'].each( function(fontSizeType) { if(fontSize.indexOf(fontSizeType)>0) { this.fontSize     = parseFloat(fontSize); this.fontSizeType = fontSizeType; } }.bind(this));  this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;  this.dims = null; if(this.options.scaleMode=='box') this.dims = [this.element.offsetHeight, this.element.offsetWidth]; if(/^content/.test(this.options.scaleMode)) this.dims = [this.element.scrollHeight, this.element.scrollWidth]; if(!this.dims) this.dims = [this.options.scaleMode.originalHeight, this.options.scaleMode.originalWidth]; }, update: function(position) { var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); if(this.options.scaleContent && this.fontSize) this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); }, finish: function(position) { if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle); }, setDimensions: function(height, width) { var d = {}; if(this.options.scaleX) d.width = Math.round(width) + 'px'; if(this.options.scaleY) d.height = Math.round(height) + 'px'; if(this.options.scaleFromCenter) { var topd  = (height - this.dims[0])/2; var leftd = (width  - this.dims[1])/2; if(this.elementPositioning == 'absolute') { if(this.options.scaleY) d.top = this.originalTop-topd + 'px'; if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; } else { if(this.options.scaleY) d.top = -topd + 'px'; if(this.options.scaleX) d.left = -leftd + 'px'; } } this.element.setStyle(d); } });
Effect.Highlight = Class.create(); Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), { initialize: function(element) { this.element = $(element); if(!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {}); this.start(options); }, setup: function() { if(this.element.getStyle('display')=='none') { this.cancel(); return; } this.oldStyle = { backgroundImage: this.element.getStyle('background-image') };this.element.setStyle({backgroundImage: 'none'}); if(!this.options.endcolor) this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); if(!this.options.restorecolor) this.options.restorecolor = this.element.getStyle('background-color');  this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this)); this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this)); }, update: function(position) { this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) }); }, finish: function() { this.element.setStyle(Object.extend(this.oldStyle, { backgroundColor: this.options.restorecolor })); } });
Effect.ScrollTo = Class.create(); Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), { initialize: function(element) { this.element = $(element); this.start(arguments[1] || {}); }, setup: function() { Position.prepare(); var offsets = Position.cumulativeOffset(this.element); if(this.options.offset) offsets[1] += this.options.offset; var max = window.innerHeight ?  window.height - window.innerHeight : document.body.scrollHeight -  (document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body.clientHeight); this.scrollStart = Position.deltaY; this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart; }, update: function(position) { Position.prepare(); window.scrollTo(Position.deltaX,  this.scrollStart + (position*this.delta)); } });
Effect.Fade = function(element) { element = $(element); var oldOpacity = element.getInlineOpacity(); var options = Object.extend({ from: element.getOpacity() || 1.0, to:   0.0, afterFinishInternal: function(effect) {  if(effect.options.to!=0) return; effect.element.hide(); effect.element.setStyle({opacity: oldOpacity});  }}, arguments[1] || {}); return new Effect.Opacity(element,options);}
Effect.Appear = function(element) {element = $(element); var options = Object.extend({ from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0), to:   1.0, afterFinishInternal: function(effect) { effect.element.forceRerendering(); }, beforeSetup: function(effect) { effect.element.setOpacity(effect.options.from); effect.element.show();  }}, arguments[1] || {}); return new Effect.Opacity(element,options); }
Effect.Puff = function(element) { element = $(element); var oldStyle = {  opacity: element.getInlineOpacity(),  position: element.getStyle('position'), top:  element.style.top, left: element.style.left, width: element.style.width, height: element.style.height }; return new Effect.Parallel( [ new Effect.Scale(element, 200,  { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),  new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],  Object.extend({ duration: 1.0,  beforeSetupInternal: function(effect) { Position.absolutize(effect.effects[0].element) }, afterFinishInternal: function(effect) { effect.effects[0].element.hide(); effect.effects[0].element.setStyle(oldStyle); } }, arguments[1] || {}) ); }
Effect.BlindUp = function(element) { element = $(element); element.makeClipping(); return new Effect.Scale(element, 0, Object.extend({ scaleContent: false,  scaleX: false,  restoreAfterFinish: true, afterFinishInternal: function(effect) { effect.element.hide(); effect.element.undoClipping(); }  }, arguments[1] || {}));}
Effect.BlindDown = function(element) { element = $(element); var elementDimensions = element.getDimensions(); return new Effect.Scale(element, 100, Object.extend({  scaleContent: false,  scaleX: false, scaleFrom: 0, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, afterSetup: function(effect) { effect.element.makeClipping(); effect.element.setStyle({height: '0px'}); effect.element.show();  }, afterFinishInternal: function(effect) { effect.element.undoClipping(); } }, arguments[1] || {})); }
Effect.SwitchOff = function(element) { element = $(element); var oldOpacity = element.getInlineOpacity(); return new Effect.Appear(element, Object.extend({ duration: 0.4, from: 0, transition: Effect.Transitions.flicker, afterFinishInternal: function(effect) { new Effect.Scale(effect.element, 1, { duration: 0.3, scaleFromCenter: true, scaleX: false, scaleContent: false, restoreAfterFinish: true, beforeSetup: function(effect) {  effect.element.makePositioned(); effect.element.makeClipping(); }, afterFinishInternal: function(effect) { effect.element.hide(); effect.element.undoClipping(); effect.element.undoPositioned(); effect.element.setStyle({opacity: oldOpacity}); }}) } }, arguments[1] || {})); }
Effect.DropOut = function(element) { element = $(element); var oldStyle = { top: element.getStyle('top'), left: element.getStyle('left'), opacity: element.getInlineOpacity() }; return new Effect.Parallel( [ new Effect.Move(element, {x: 0, y: 100, sync: true }), new Effect.Opacity(element, { sync: true, to: 0.0 }) ], Object.extend( { duration: 0.5, beforeSetup: function(effect) { effect.effects[0].element.makePositioned(); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide(); effect.effects[0].element.undoPositioned(); effect.effects[0].element.setStyle(oldStyle); }  }, arguments[1] || {}));}
Effect.Shake = function(element) { element = $(element); var oldStyle = { top: element.getStyle('top'), left: element.getStyle('left') }; return new Effect.Move(element, { x:  20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) { new Effect.Move(effect.element, { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { effect.element.undoPositioned(); effect.element.setStyle(oldStyle); }}) }}) }}) }}) }}) }}); }
Effect.SlideDown = function(element) { element = $(element); element.cleanWhitespace(); var oldInnerBottom = $(element.firstChild).getStyle('bottom'); var elementDimensions = element.getDimensions(); return new Effect.Scale(element, 100, Object.extend({ scaleContent: false,  scaleX: false,  scaleFrom: window.opera ? 0 : 1, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, afterSetup: function(effect) { effect.element.makePositioned(); effect.element.firstChild.makePositioned(); if(window.opera) effect.element.setStyle({top: ''}); effect.element.makeClipping(); effect.element.setStyle({height: '0px'}); effect.element.show(); }, afterUpdateInternal: function(effect) { effect.element.firstChild.setStyle({bottom: (effect.dims[0] - effect.element.clientHeight) + 'px' }); }, afterFinishInternal: function(effect) { effect.element.undoClipping();  if(/MSIE/.test(navigator.userAgent) && !window.opera){ effect.element.undoPositioned(); effect.element.firstChild.undoPositioned(); }else{ effect.element.firstChild.undoPositioned(); effect.element.undoPositioned(); } effect.element.firstChild.setStyle({bottom: oldInnerBottom}); } }, arguments[1] || {}) ); }
Effect.SlideUp = function(element) { element = $(element); element.cleanWhitespace(); var oldInnerBottom = $(element.firstChild).getStyle('bottom'); return new Effect.Scale(element, window.opera ? 0 : 1, Object.extend({ scaleContent: false,  scaleX: false,  scaleMode: 'box', scaleFrom: 100, restoreAfterFinish: true, beforeStartInternal: function(effect) { effect.element.makePositioned(); effect.element.firstChild.makePositioned(); if(window.opera) effect.element.setStyle({top: ''}); effect.element.makeClipping(); effect.element.show(); }, afterUpdateInternal: function(effect) { effect.element.firstChild.setStyle({bottom: (effect.dims[0] - effect.element.clientHeight) + 'px' }); }, afterFinishInternal: function(effect) { effect.element.hide(); effect.element.undoClipping(); effect.element.firstChild.undoPositioned(); effect.element.undoPositioned(); effect.element.setStyle({bottom: oldInnerBottom}); } }, arguments[1] || {}) ); }
Effect.Squish = function(element) { return new Effect.Scale(element, window.opera ? 1 : 0,  { restoreAfterFinish: true, beforeSetup: function(effect) { effect.element.makeClipping(effect.element); },   afterFinishInternal: function(effect) { effect.element.hide(effect.element);  effect.element.undoClipping(effect.element); } }); }
Effect.Grow = function(element) { element = $(element); var options = Object.extend({ direction: 'center', moveTransition: Effect.Transitions.sinoidal, scaleTransition: Effect.Transitions.sinoidal, opacityTransition: Effect.Transitions.full }, arguments[1] || {});  var oldStyle = { top: element.style.top, left: element.style.left, height: element.style.height, width: element.style.width, opacity: element.getInlineOpacity() };  var dims = element.getDimensions();  var initialMoveX, initialMoveY; var moveX, moveY; switch (options.direction) { case 'top-left': initialMoveX = initialMoveY = moveX = moveY = 0;  break; case 'top-right': initialMoveX = dims.width; initialMoveY = moveY = 0; moveX = -dims.width; break; case 'bottom-left': initialMoveX = moveX = 0; initialMoveY = dims.height; moveY = -dims.height; break; case 'bottom-right': initialMoveX = dims.width; initialMoveY = dims.height; moveX = -dims.width; moveY = -dims.height; break; case 'center': initialMoveX = dims.width / 2; initialMoveY = dims.height / 2; moveX = -dims.width / 2; moveY = -dims.height / 2; break; } return new Effect.Move(element, { x: initialMoveX, y: initialMoveY, duration: 0.01,  beforeSetup: function(effect) { effect.element.hide(); effect.element.makeClipping(); effect.element.makePositioned(); }, afterFinishInternal: function(effect) { new Effect.Parallel( [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), new Effect.Scale(effect.element, 100, { scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})], Object.extend({ beforeSetup: function(effect) { effect.effects[0].element.setStyle({height: '0px'}); effect.effects[0].element.show();  }, afterFinishInternal: function(effect) { effect.effects[0].element.undoClipping(); effect.effects[0].element.undoPositioned(); effect.effects[0].element.setStyle(oldStyle);  } }, options))} }); }
Effect.Shrink = function(element) { element = $(element); var options = Object.extend({ direction: 'center', moveTransition: Effect.Transitions.sinoidal, scaleTransition: Effect.Transitions.sinoidal, opacityTransition: Effect.Transitions.none }, arguments[1] || {}); var oldStyle = { top: element.style.top, left: element.style.left, height: element.style.height, width: element.style.width, opacity: element.getInlineOpacity() }; var dims = element.getDimensions(); var moveX, moveY; switch (options.direction) { case 'top-left': moveX = moveY = 0; break; case 'top-right': moveX = dims.width; moveY = 0; break; case 'bottom-left': moveX = 0; moveY = dims.height; break; case 'bottom-right': moveX = dims.width; moveY = dims.height; break; case 'center':   moveX = dims.width / 2; moveY = dims.height / 2; break; } return new Effect.Parallel( [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) ], Object.extend({beforeStartInternal: function(effect) { effect.effects[0].element.makePositioned(); effect.effects[0].element.makeClipping(); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide(); effect.effects[0].element.undoClipping(); effect.effects[0].element.undoPositioned(); effect.effects[0].element.setStyle(oldStyle); }}, options) );}
Effect.Pulsate = function(element) { element = $(element); var options    = arguments[1] || {}; var oldOpacity = element.getInlineOpacity(); var transition = options.transition || Effect.Transitions.sinoidal; var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) }; reverser.bind(transition); return new Effect.Opacity(element,  Object.extend(Object.extend({  duration: 3.0, from: 0,afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } }, options), {transition: reverser})); }
Effect.Fold = function(element) { element = $(element); var oldStyle = { top: element.style.top, left: element.style.left, width: element.style.width, height: element.style.height }; Element.makeClipping(element); return new Effect.Scale(element, 5, Object.extend({ scaleContent: false, scaleX: false, afterFinishInternal: function(effect) { new Effect.Scale(element, 1, {  scaleContent: false,  scaleY: false, afterFinishInternal: function(effect) { effect.element.hide(); effect.element.undoClipping();  effect.element.setStyle(oldStyle); } }); }}, arguments[1] || {})); }; ['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom', 'collectTextNodes','collectTextNodesIgnoreClass','childrenWithClassName'].each( function(f) { Element.Methods[f] = Element[f]; }); Element.Methods.visualEffect = function(element, effect, options) { s = effect.gsub(/_/, '-').camelize(); effect_class = s.charAt(0).toUpperCase() + s.substring(1); new Effect[effect_class](element, options); return $(element); };
Element.addMethods();var file_select  = function(selectedIndex){	
	for(i=0; i<document.writeForm.b_file_name.length; i++) {
		document.writeForm.b_file_name.options[i].selected = false;
    }
    document.writeForm.b_file_name.options[selectedIndex].selected = true;
}

var addFile = function(host, port) {
	var theform = document.writeForm;
    if($("upload").value=="") {
    	Dialog.message("첨부할 파일을 선택해주세요.");
        return;
    }
	if((/(.jpg|.jpeg|.gif|.png|.bmp)$/i).test($("upload").value)){
    	Dialog.message("이미지 파일은 첨부파일로 올리실수 없습니다.");
		return;
	}
    theform.target = "actionFrame";
	theform.action = "http://"+host+".ohpy.com:"+port+"/opftp/index.php?control=Upload";
    theform.submit();
}


var addFileAction = function(filepath, filename, filesize, target){
	var o		= document.createElement("option");
	o.setAttribute('value' , "NULL&^&"+filepath+'&^&'+filename+'&^&'+filesize);
	html = filename+'('+Math.ceil(parseInt(filesize)/1000)+'KB)';
	o.appendChild(document.createTextNode(html));
	$(target).appendChild(o);
}

// 멀티미디어 링크 걸기
var popeditmedia = function(op_no,targetFrame){
	var url			= "/pop_add_link.php?op_no="+op_no+"&target_frame="+targetFrame+'&nocache='+Math.random();
	 window.open(url, "winMedia", "width=400, height=355");
	 return;
}
// 이미지 넣기
var popeditimage = function(op_no,bbs_no,targetFrame, imgMaxWidth){
	var url			= "/opbbs/index.php?control=Write&branch=image_upload_form&op_no="+op_no+"&bbs_no="+bbs_no+"&target_frame="+targetFrame+ "&img_max_width=" + imgMaxWidth + "&nocache="+Math.random();
	 window.open(url, "winEditImage", "width=417, height=355 , scrollbars=1,resizable=no,status=0");
	 return;
}

var imageFileAction =  function(filepath, filename, filesize, target){
	var o		= document.createElement("option");
	o.text	= filename+'('+Math.ceil(parseInt(filesize)/1000)+'KB)';
	o.value = "NULL&^&"+filepath+'&^&'+filename+'&^&'+filesize;
	try {
		$(target).add(o,null);
	}
	catch(e) {
		$(target).add(o);
	}
}

// 이미지 링크 걸기
var editer_add_rink = function(target_frame, szhtml){
	window.frames[target_frame].AddInnerHTML(szhtml);
}
// 멀티미디어 링크 걸기
var editer_add_media = function(target_frame, szhtml){
	window.frames[target_frame].AddInnerHTML(szhtml);
}

// 셧터기능
ajax.getshutContent = function(array) {
	// 해당 클래스가 있으면 
	var actiondiv = "blind_" + array[4];
	array[4] = "div_content" + array[4];
	if(Element.hasClassName($(actiondiv),"elbbs-icon-article-hide")){
		Element.removeClassName($(actiondiv),"elbbs-icon-article-hide");
		Element.addClassName($(actiondiv),"elbbs-icon-article-view");
		Effect.toggle($(array[4]),"BLIND");
		var arrEmbedTag = $(array[4]).getElementsByTagName('embed');
		$A(arrEmbedTag).each(function(arg){
			arg.stop();
		});
	}else{
		Element.addClassName($(actiondiv),"elbbs-icon-article-hide");	
		ajax.post(array);
	}
}

Object.extend(ajax, {
	writeauth:function(fields){
		element = Element.getDescendantByClassName($(fields['form']),'authbox');
		msginfo = Element.getDescendantByClassName(element,'auth-msg');
		var aElems=element.getElementsByTagName('input');
		if(!aElems[0].value.trim()){
			msginfo.innerHTML = '이름을 입력해주세요.';
			return;
		}
		if(!aElems[1].value.trim()){
			msginfo.innerHTML = '패스워드를 입력해주세요.';
			return;
		}
		this.repl(fields);
	},
	pwdauth:function(fields){
		element = Element.getDescendantByClassName($(fields['form']),'authbox-middle');
		msginfo = Element.getDescendantByClassName(element,'auth-msg');
		var aElems=element.getElementsByTagName('input');
		if(!aElems[0].value.trim()){
			msginfo.innerHTML = '패스워드를 입력해주세요.';
			return;
		}
		fields['div'] = msginfo;
		this._send(fields);
	},
	editauth:function(fields){
		element = Element.getDescendantByClassName($(fields['form']),'authbox');
		msginfo = Element.getDescendantByClassName(element,'auth-msg');
		var aElems=element.getElementsByTagName('input');
		if(!aElems[0].value.trim()){
			msginfo.innerHTML = '패스워드를 입력해주세요.';
			return;
		}
		fields['div'] = msginfo;
		this.repl(fields);
	},
	pwdSecretViewAuth:function(fields){
		element = Element.getDescendantByClassName($(fields['form']),'secret');
		var aElems=element.getElementsByTagName('input');
		if(!aElems[0].value.trim()){
			Dialog.message('패스워드를 입력해주세요.');
			return;
		}
		fields['div'] = element;
		this._send(fields);
	},
	authwrite:function(fields){
		// logion check
		if(!getCookie("opTicket")){
			Dialog.message("로그인을 해주세요.");
			return;
		}
		var arrCookie = getPlainCookie("opPlainTicket");
		ScriptLoader.AddScript('/js/calendar.js');
		ScriptLoader.AddScript('http://img.ohpy.com/opimg/common/calendar/style.css');
		if(arrCookie['is_checked_name'] == "Y"){
			this._send(fields);
		}else{
			var op_no = $("op_no").value;
			var bbs_no = $("bbs_no").value;
			var szUrl = "/opuser/";
			var szQuery = "control=NameCheck&branch=name_auth&action_type=write&op_no="+op_no+"&bbs_no="+bbs_no;
			Dialog.nameAuth({windowParameters: {className: "memberbox-container", width:700, height:560}, authInfo: {uri:szUrl, query:szQuery}});
		}
	},
	repl:function(fields){
		element = $(fields['form']);
		var aElems=element.getElementsByTagName('textarea');
		if(aElems.length>0){
			if(!aElems[0].value.trim()){
				Dialog.message(bbs_lang['INPUT_CONTENT'][fields['lang']]);
				return;
			}
			this._send(fields);
		}
	},
	check_status:false,
	check_all:function(){
		var someNodeList = $('list').getElementsByTagName('input');
		var nodes = $A(someNodeList);
		nodes.each(function(node){
			if(node.type == "checkbox"){
				if(!ajax.check_status){
					node.checked = true;
				}else{
					node.checked = false;
				}
			}
		});
		ajax.check_status = !ajax.check_status;
	},
	get_checklist:function(){
		var b_no_list = "";
		var someNodeList = $('list').getElementsByTagName('input');
		var nodes = $A(someNodeList);
		nodes.each(function(node){
			if(node.type == "checkbox" && node.name == "b_no[]"){
				if(node.checked == true){
					b_no_list += node.value + "&";
				}
			}
		});
		return b_no_list;
	},
	// 삭제되는 글이 있나 없나 체크해준다	
	_deleteboard:function(fields){
		var b_no = this.get_checklist();
		if(b_no == ""){
			Dialog.message("삭제할 글을 선택해주세요.");
		}else{
			if(confirm("정말로 게시물을 삭제하시겠습니까?")){
				$('list_b_no').value = b_no;
				this._send(fields);
			}
		}
	},
	_bnoMove:function(fields){
		var b_no = this.get_checklist();
		if(b_no == ""){
			Dialog.message("이동할 글을 선택주세요.");
		}else{
			this._send(fields);
		}
	},
	// 리스트 선택한 영역 이동부분	
	list_move_apply:function(fields){
		var b_no = ajax.get_checklist();	
		// 이동되는 글이 있나 없나 체크해준다
		if(b_no == ""){
			Dialog.message('이동할 글을 선택주세요.');
			return;
		}else if($F('targetBbsSel') == "-2"){
			Dialog.message('대상 게시판을 선택해주세요.');
			return;
		} else if($F('targetCategorySel') == "-2"){
			Dialog.message('대상 카테고리를 선택해주세요.');
			return;
		} else {
			if(confirm("정말로 게시물을 이동하시겠습니까?")){
				$('move_b_no').value = b_no;
				this._send(fields);
				return;
			}
		}
	},
	deleteBno:function(fields){
		if(getCookie("opTicket")){
			if(confirm("정말로 게시물을 삭제하시겠습니까?")){
				this._send(fields);
			}
		}
	},
	_getNotice:function(fields){
		var params = fields['query'].toQueryParams();
		var element = $(fields['div']);
		if(element.style.display == "none"){
			this._send(fields);
		}else{
			Element.update(element, '');
			Element.hide(element);
		}
	},
	notLoginBoardWrite:function(fields){
		$('b_content').value =  Editer.showHTML();
		if($F('b_content').trim() == ""){
	   		Dialog.message("내용을 입력해주세요.");
			return;
		}
		
		this._send(fields);
	},
	foldRepl:function(fields){
		var params = fields['query'].toQueryParams();
		var title = $("react_title["+params['b_no']+"]");
		var body = $("react_body["+params['b_no']+"]");
		if(Element.hasClassName(title,'reply-open')){
			Element.removeClassName(title,'reply-open');
			Element.hide(body);
		}else{
			this._send(fields);
		}
	},
	foldTrb:function(fields){
		var params = fields['query'].toQueryParams();
		var title = $("react_title["+params['b_no']+"]");
		var body = $("react_body["+params['b_no']+"]");
		if(Element.hasClassName(title,'trackback-open')){
			Element.removeClassName(title,'trackback-open');
			Element.hide(body);
		}else{
			this._send(fields);
		}
	},
	_deleteFile:function(fields){
		var obj	= $('b_file_name');
		var selectCnt	= obj.length;	
		var sIdx =	obj.selectedIndex;
		if(sIdx < 0) {
			Dialog.message("삭제할 파일을 선택해주세요.");
			return;
		}
		this._send(fields);
		for(var i=selectCnt-1; i >=0 ;i--){
			if (obj.options[i].selected == true){
				obj.options[i]	= null;
			}
	 	}
		obj.selectedIndex = -1;
	},
	bbsPreview:function(fields) {
		var params = fields['query'].toQueryParams();
		var actiondiv = "blind_" + params['b_no'];
		if(Element.hasClassName($(actiondiv),"icon-article-hide")){
			Element.removeClassName($(actiondiv),"icon-article-hide");
			Element.addClassName($(actiondiv),"icon-article-view");
			Effect.toggle($(fields['div']),"BLIND");
			var arrEmbedTag = $(fields['div']).getElementsByTagName('embed');
			$A(arrEmbedTag).each(function(arg){
				arg.stop();
			});
		}else{
			Element.addClassName($(actiondiv),"icon-article-hide");	
			this._send(fields);
		}
	},
	bbspost : function(fields){
		// 파일정보 무조건 selected
		if($("b_file_name") != undefined){
			var obj		= $("b_file_name");
			var selectCnt	= obj.length;	
		
			$A(obj).each(function(arg){
				arg.selected = false;
			});
			var tmpvalue = "";
			for (var i=0; i< selectCnt; i++){
				tmpvalue += obj.options[i].value+"&FILE&";
			}
		
			if(selectCnt > 0){
				Field.clear(obj);
				obj.options[0].selected = true;
				obj.options[0].value = tmpvalue;
			}
		}
		// 제목
		if($F("b_subject").trim() == ""){
			Dialog.message(bbs_lang['INPUT_TITLE'][fields['lang']]);
			return;
		}
		$('b_content').value = Editer.showHTML().stripScripts();
		
		// 클립보드 저장하기
		if($("use_clipboard") != undefined){
			if( $("use_clipboard").value == "Y") {
				var tmp = $('b_content').value;
				tmp = removeEtc(tmp);
				tmp = tmp.br2nl();	
				tmp = removeHTML(tmp);
				copy_clip(tmp);
			}
		}
		this._send(fields);
	},
	notLoginpost : function(fields){
		var form			= fields[0];
		var query			= fields[1];
		var parameter	= fields[2];
		// 파일정보 무조건 selected
		if($("b_file_name") != undefined){
			var obj		= $("b_file_name");
			var selectCnt	= obj.length;	
			var tmpvalue = "";
			for (var i=0; i< selectCnt; i++){
				tmpvalue += obj.options[i].value+"&FILE&";
			}
			if(selectCnt > 0){
				obj.options[0].selected = true;
				obj.options[0].value = tmpvalue;
			}
		}
		if($F("b_subject").trim() == "") {
			Dialog.message(bbs_lang['INPUT_TITLE'][fields['lang']]);
			return;
		}
		$('b_content').value = Editer.showHTML();
		this._send(fields);
	}
});

var changeCategory = function(op_no,bbs_no) {
	var data = new Array();
	data[0] = "/opbbs/index.php";
	data[1] = "";
	data[2] = "post";
	data[3] = "control=Move&op_no=" + op_no + "&bbs_no=" + bbs_no + "&branch=get_category" ;
	data[4] = "targetCategory";
	ajax.post(data);
}

var checkCheckBox = function(col_name) {
    var theform = document.searchForm;
    for(var j = 0; j<theform.elements.length; j++) {
        if(theform.elements[j].checked){
            return;
        }
    }
    theform.elements[0].checked=true;
    return;
}

var togCheckBox = function(col_name) {
    var theform = document.searchForm;
    for(var j = 0; j<theform.elements.length; j++) {
        if(theform.elements[j].value == col_name) {
            if(theform.elements[j].checked) {
                theform.elements[j].checked=false;
            } else {
                theform.elements[j].checked=true;
            }
        }
    }
    checkCheckBox(col_name);
    return;
}

// 안전거래사용여부
var checkSafepay	= function(obj){
	chekboxs	= Form.getInputs("writeForm", "checkbox", "pay_method[]");
	if(obj.checked){
		for(var i=0; i < chekboxs.length; i++){
			chekboxs[i].disabled = false;
		}
	}else{
		for(var i=0; i < chekboxs.length; i++){
			chekboxs[i].disabled = true;
		}
	}
	return;
}
// 해당년월의 마지막 날짜를 구한다
var getLastDay = function(year, month){
	var lastDay;
	if(month == 1		|| month == 3		|| month == 5		|| month == 7		|| month == 8		|| month == 10		|| month == 12	)	lastDay = 31;
	else if(month == 4		|| month == 6		|| month == 9		|| month == 11	)		lastDay = 30;
	else{
		if((year % 400) == 0) lastDay = 29;
		else if((year % 100) == 0) lastDay = 28;
		else if((year % 4) == 0) lastDay = 29;
		else lastDay = 28;
	}
	return lastDay;
}
// 유효한 날짜인지 Check 
var isValidCheckDate = function(szDate) {
	szDate = szDate.trim();
	var parmLen = szDate.length;
	if(parmLen!=8 && parmLen!=10) {
		return(false);
	}
	if(parmLen==10)  szDate = szDate.substring(0,4) + szDate.substring(5,7) + szDate.substring(8,10);
	if(!Is_number(szDate)) {
		return(false);
	}
	var yyyy = szDate.substring(0,4);
	var mm   = szDate.substring(4,6);
	var dd   = szDate.substring(6,8);
	if(yyyy<1900) {
		return(false);
	}
	if(mm>12 || mm<1) {
		return(false);
	}
	var lastDay = getLastDay(yyyy,mm);
	if(dd<1 || dd>lastDay) {
		return(false);
	}
	return(true);
}


// 유효한 시간인지 Check 
var isValidCheckTime = function(szDate) {
	szDate = szDate.trim();
	var parmLen = szDate.length;
	if(parmLen!=6) return(false);
	if(!Is_number(szDate)) return(false);
	var hh = parseInt(szDate.substring(0,2));
	var ii   = parseInt(szDate.substring(2,4));
	var ss   = parseInt(szDate.substring(4,6));
	if(hh>24 || hh < 0) return(false);
	if(ii <0 || ii>60) return(false);
	return(true);
}

// 시간 체크 
var IsValidFromTime = function(from_time, to_time){
	if(!isValidCheckTime(from_time)){
		Dialog.message("시작시간이 유효하지 않습니다.");
		return false;
	}
	if(!isValidCheckTime(to_time)){
		Dialog.message("마감시간이 유효하지 않습니다.");
		return false;
	}	
	return true;
}

// date 체크 
var IsValidFromDate = function(from_date, to_date){
	if(!isValidCheckDate(from_date)){
		Dialog.message("시작일자가 유효하지 않습니다.");
		return false;
	}
	if(!isValidCheckDate(to_date)){
		Dialog.message("마감일자가 유효하지 않습니다.");
		return false;
	}	
	if(parseInt(from_date,10) > parseInt(to_date,10)){
		Dialog.message("시작일자가 마감일자보다 미래의 날짜입니다.");
		return false;
	}	
	return true;
}

// 날짜 체크
var isDataCheck = function(start_date, end_date){
	var arrFromdate = start_date.split(' '); 
	var arrTodate = end_date.split(' ');
	var from_date = clearDelimit(arrFromdate[0], "-");
	var to_date = clearDelimit(arrTodate[0], "-");
	//시작일, 종료일 check
	if(!IsValidFromDate(from_date,to_date)){
		return false;
	}
	var from_time = clearDelimit(arrFromdate[1], ":");
	var to_time = clearDelimit(arrTodate[1], ":");
	//시작시간, 종료시간 check
	if(!IsValidFromTime(from_time,to_time)){
		return false;
	}
	
	start_date = 	from_date+from_time;
	end_date = to_date+to_time;
	if(parseInt(start_date) > parseInt(end_date)){
		Dialog.message("시작일자가 마감일자보다 미래의 날짜입니다.");
		return false;
	}
	return true;
}

// cobuy action
var checkWriteForm = function(obj) {
	// login check
	if(!getCookie("opTicket")){
		Dialog.message("로그인을 해주세요.");
		return;
	}
	// 글제목
	if($F("b_subject") == ""){
		Dialog.message("제목을 입력해주세요.");
		return;
	}
	// 상품정보
	if($F("product_name") == ""){
		Dialog.message("상품명을 입력해주세요.");
		return;
	}
	// 상품 가격
	$('product_price').value = $('product_price').value.replace(/[,]*/g,"");
	if($F("product_price") == ""){
		Dialog.message("상품가격을 입력해주세요.");
		return;
	}else{
		if(!Is_number($F("product_price"))){
			Dialog.message("상품가격은 숫자로 구성되어야 합니다.");
			return;
		}
		if( $F("product_price")  < 1000){
			Dialog.message("등록하실수 있는 상품의 최저가격은 <br> 1000원 이상 입니다.");
			return;
		}
	}

	if($F("bbs_type") == "cobuy"){
		// 상품 수량
		if($F("product_cnt") == "" || $F("product_cnt") == "0"){
			Dialog.message("상품수량을 입력해주세요.");
			return;
		}else{
			if(!Is_number($F("product_cnt"))){
				Dialog.message("상품수량은 숫자로 구성되어야 합니다.");
				return;
			}
		}
		// 주문가능 수량
		if($F("buycnt_by_one") == ""){
			Dialog.message("주문가능 수량을 입력해주세요.");
			return;
		}else{
			if(!Is_number($F("buycnt_by_one"))){
				Dialog.message("주문가능 수량은 숫자로 구성되어야 합니다.");
				return;
			}
		}
		// 날짜 체크
		var start_date = $F("b_start_date");
		start_date = start_date+":00";	
		var end_date = $F("b_end_date");
		end_date = end_date+":00";	
		if(!isDataCheck(start_date, end_date)){
			return;
		}
	}
	
	// 안전결재 && 결재방법
	if($("is_safe_pay").checked){
		var safecnt = 0;
		chekboxs	= Form.getInputs("writeForm", "checkbox", "pay_method[]");
		for(var i=0; i < chekboxs.length; i++){
			if(chekboxs[i].checked){
				safecnt ++;
			}
		}
		if(safecnt < 1){
			Dialog.message("결제방법을 한개이상 선택하셔야 합니다.");
			return;
		}
	}
		
	// 판매자
	if($F("seller_name") == ""){
		Dialog.message("판매자를 입력해주세요.");
		return;
	}

	// 연락처
	if(($F("seller_phone1_1") == "") || ($F("seller_phone1_2") == "") ||($F("seller_phone1_3") == "")){
		Dialog.message("연락처를 입력해주세요");
		return;
	}else{
		if(!Is_number($F("seller_phone1_1"))){
			Dialog.message("연락처를 입력해주세요");
			return;
		}
		if(!Is_number($F("seller_phone1_2"))){
			Dialog.message("연락처를 입력해주세요");
			return;
		}		
		if(!Is_number($F("seller_phone1_3"))){
			Dialog.message("연락처를 입력해주세요");
			return;
		}
	}
			
	// 주소찾기
	if( $("seller_zipcode") == undefined){
		Dialog.message('주소찾기 버튼을 클릭하여 주소를 검색해주세요');
		return;
	}else{
		$("seller_address1").value = $('seller_zipcode')[$('seller_zipcode').selectedIndex].text;
	}

	// 주소 2
	if($F("seller_address2") == ""){
		Dialog.message("상세주소를 입력해주세요.");
		return;
	}

	// 이미지 확장자 체크
	if($("seller_uplxoad[]") != undefined){
		arrProduct	= Form.getInputs("writeForm", "file", "seller_upload[]");
		for(var i=0; i < arrProduct.length; i++){
			if(arrProduct[i].value == "") continue;
			if(!(/(.jpg|.jpeg|.gif|.png)$/i).test(arrProduct[i].value)){
				Dialog.message('상품이미지는 gif, jpg, png 파일만 가능합니다.');
				return;
			}
		}
	}

	var theform = document.writeForm;
    theform.target = "actionFrame";
	$("upload_type").value = obj.upload_type;
	$("return_url").value = obj.return_url ;
    theform.action = "http://pic"+obj.host+".ohpy.com/opftp/index.php?control=Upload";
   	
   	
    theform.submit();
}

// cobuy 이미지 변환 
var change_img = function(atag_target, image_path, image_name) {
	var mid_image = image_path + "mid_" + image_name;
	var full_image = image_path + image_name;
	$(atag_target).setStyle({backgroundImage : "url("+mid_image+")"});
	$(atag_target).href = full_image; 
}

// 캘린더 부분
var showCalendar = function(id, input_target, a_target){
	var obj = $(input_target);
	var server_tm = obj.value;
	var useCheck = id+"_calendar";
	if($(useCheck) == undefined){
		var calrendar = new Calendar(id,obj,server_tm);
		a_target.onclick = function () {calrendar.show();} 
	}
	return;
}
// 구매 input File 속성
var changeInputFile = function(target,orderNo){
	new Insertion.Before(target,'<input type="file" class="file" size="48" id="seller_upload[]" name="seller_upload[]" />');
	Element.remove(target);
	var szImage = "img_type"+orderNo;
	$(szImage).value = "NEW";
	return;	
}

// SCRIPT 주민번호 유효성 검사
var isjuminnumCheck = 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;
}

ajax.nameAuth = function(array){
	var name = $("u_name").value;
	var res1 = $("resident_num1").value;
    var res2 = $("resident_num2").value;
    var div = $("auth_msg");
    if(name == ""){
   		div.innerHTML = '이름을 입력해주세요.';
		Field.focus("u_name");
   		return;
    }
	if(res1.trim() == "") {
		div.innerHTML = '주민등록번호 앞자리를 입력해주세요.';
        Field.focus("resident_num1");
	    return;
	} else if(res2.trim() == "") {
		div.innerHTML = '주민등록번호 뒷자리를 입력해주세요.';
        Field.focus("resident_num2");
	    return;
	}
	// 주민번호 유효성 검사
	if(!isjuminnumCheck(res1, res2)){
		div.innerHTML = '잘못된 주민번호 형식입니다.';	
		return;
	}
	if(!Is_number(res1)){
		div.innerHTML = '잘못된 주민번호 형식입니다.';
		return;
	}
	if(!Is_number(res2)){
		div.innerHTML = '잘못된 주민번호 형식입니다.';	
		return;
	}	
	if(res1.length < 6) {
		div.innerHTML = '주민등록번호 앞자리는 6자리입니다.';	
        Field.focus("resident_num1");
	    return;	
	} else if(res2.length < 7) {
		div.innerHTML = '주민등록번호 뒷자리는 7자리입니다.';
        Field.focus("resident_num2");
	    return;	
	}
	ajax.post(array);
}

var authrealname = function(method,is_safe_pay){
	// logion check
	if(!getCookie("opTicket")){
		Dialog.message("로그인을 해주세요.");
		return;
	}
	// real name check
	var arrCookie = getPlainCookie("opPlainTicket");
	// confirm
	if(arrCookie['is_checked_name'] == "Y"){
		if(method == "authcobuy"){
			var totalcnt = $("product_cnt").value;
			var requestcnt = parseInt($("sold_cnt").value) + parseInt($("order_cnt").value);
			if($("order_cnt").value == ""){
				Dialog.message("주문 수량을 입력해주세요.");
				return;
			}
			if(parseInt($("buycnt_by_one").value) < parseInt($("order_cnt").value)){
				Dialog.message("1인당 "+parseInt($("buycnt_by_one").value)+"개까지 신청하실수 있습니다.");
				return;
			}
			if(totalcnt < requestcnt){
				Dialog.message("주문가능한 수량을 초과하셨습니다.");
				return;
			}
			$("buycnt").value = $("order_cnt").value;
		}
		ajax._send({ url : "/opbbs/index.php", query : "control=View&branch=buy_product&op_no="+$("ohpyno").value+"&bbs_no="+$("ohpybbsno").value+"&b_no="+$("ohpybbsseqno").value+"&buycnt="+$("buycnt").value, div : "common_action", form :"", method : "get" });
	}else{
		var szUrl = "/opuser/index.php";
		var szQuery = "control=NameCheck&branch=name_auth&action_type="+method;
		Dialog.nameAuth({windowParameters: {className: "memberbox-container", width:700, height:560}, authInfo: {uri:szUrl, query:szQuery}});
	}
	return;
}

var authFrame = function(szUrl){
	// logion check
	if(!getCookie("opTicket")){
		Dialog.message("로그인을 해주세요.");
		return;
	}
	// real name check
	var arrCookie = getPlainCookie("opPlainTicket");
	
	// confirm
	if(arrCookie['is_checked_name'] == "Y"){ 
		Dialog.iframe({windowParameters: {className: "memberbox-container", url :szUrl, width:700, height:560}});
		var theform = document.applybuyForm;
		theform.target ="common_dialog_content";
		theform.action = szUrl;
		theform.submit();
	}
}

var newprice = function(obj){
	var Num = obj.value.replace(/,/g,'');
	obj.value = obj.value.replace(/,/g,'');

	Num = (Num+'')
	var commaFlag = Num.length%3;
	if(commaFlag) {
		var out = Num.substring(0, commaFlag) 
		if (Num.length > 3) out += ','
	}	else var out = ''

	for (var i=commaFlag; i < Num.length; i+=3) {
		out += Num.substring(i, i+3) 
		if( i < Num.length-3) out += ','
	}
	obj.value = out;
	return;	
}

// clipboard 복사하기.
var copy_clip = function(meintext) {
	try {
		if (window.clipboardData) { 
			window.clipboardData.setData("Text", meintext);
		}else if (window.netscape) {
			netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
			var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
			if (!clip) return;
			var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
			if (!trans) return;
			trans.addDataFlavor('text/unicode');
			var str = new Object();
			var len = new Object();
			var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
			var copytext=meintext;
			str.data=copytext;
			trans.setTransferData("text/unicode",str,copytext.length*2);
			var clipid=Components.interfaces.nsIClipboard;
			if (!clip) return false;
			clip.setData(trans,null,clipid.kGlobalClipboard);
		}
		return false;
	} catch(e) {
	}
}



// 문자열 중에 HTML 소스 없애기
var removeHTML = function(string) {
  var objStrip = new RegExp();
  objStrip = /[<][^>]*[>]/gi;
  return string.replace(objStrip, "");
}

// 필요없는 문자 제거.
var removeEtc = function(string) {
	var objStrip = new RegExp();
	objStrip = /&nbsp;/gi;
	string = string.replace(objStrip, " ");
	if(window.netscape) {
		objStrip = /\n/gi;
		return string.replace(objStrip, "");
	} else {
		return string;
	}
}

// 프린트용 팝업
var popPrint = function(op_no,bbs_no,b_no) {
	 var url			= "/opbbs/?control=View&branch=print_css&op_no="+op_no+"&bbs_no="+bbs_no+"&b_no="+b_no + "&nocache="+Math.random();
	 window.open(url, "winPrint", "width=695, height=600 , resizable=no,status=0,scrollbars=1");
	 return;
}

// 게시판용 함수
var Bbs = {};
Object.extend(Bbs,{
	selectBox: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){
		}
	}
});

bbs_lang=new Array();
bbs_lang['INPUT_TITLE'] = {"KR" : "제목을 입력해주세요.", "EN" : "Please enter the title."};
bbs_lang['INPUT_CONTENT'] = {"KR" : "내용을 입력해주세요.", "EN" : "Please enter the content."};/**
 * Tooltip.js
 *
 * Advanced Tooltip class
 *
 * WARNING: Due to an IE bug, Tooltips will NOT display on top of a <select> element.
 *
 * @copyright Davey Shafik (c) 2005 All Rights Reserved
 * @authors Davey Shafik <davey@php.net>
 * @version 0.6.0
 * @license MIT-style <http://tooltip.crtx.org/LICENSE>
 * @todo Fix accessibility, make it possible to tab in/out of tooltips, and look into CSS Voice stuff
 * @todo Add ability to change the events *per* Tooltip
 */

/**
 * Add an Array.contains() method, mimics PHPs in_array() function
 */

Array.prototype.contains = function (value)
{
	for (var i = 0; i < this.length; i++) {
		if (this[i] == value) {
			return true;
		}
	}
	return false;
}

/**
 * Tooltip Object definition
 */
var Tooltip = {
	/**
	 * @var string|Array An event name or an array of event names on which to trigger showing the Tooltip
	 */
	showEvent: "click",

	/**
	 * @var string|Array An event name or an array of event names on which to trigger hiding the Tooltip
	 */
	hideEvent: "click",

	/**
	 * @var float Duration of the fade events, in seconds
	 * @author Idea contributed by Richard Thomas <cyberlot@cyberlot.net>
	 */
	fade: 0.3,

	/**
	 * @var string Close Link Text
	 */
	closeText: "",

	/**
	 * @var function Set the method which will be called for showing the tooltip
	 */
	showMethod: Effect.Appear,

	/**
	 * @var function Set the method which will be called for hiding the tooltip
	 */
	hideMethod: Effect.Fade,

	/**
     * @var boolean Whether the Tooltip should follow the mouse or not. Warning: Cheesy!
     */
    autoFollowMouse: false,

	/**
	 * @var integer If set, the Tooltip will automatically hide after X seconds
     *
     * When followMouse is true, the mouseout event does not trigger the hide callback
     * till X has passed. This is to allow the user to move a little off the element -
     * which is especially useful when it's an inline element such as a link.
     */
    autoHideTimeout: 40,

	/**
	 * @var boolean Allow user to click anywhere to hide current tooltip
	 */
	autoHideClick: true,

	/**
	 * @var boolean If set to true, the Tooltip will be displayed (static) at the current Mouse Cursor location.
	 */
	autoMoveToCursor: true,

	/**
	 * @const int Indicate that the current tooltip should be used
	 */
	CURRENT_TOOLTIP: 2,

	/**
	 * @var object Currently shown Tooltip
	 */
	_current: false,

	/**
	 * Initial Setup
	 *
	 * Find all standard tooltips and auto-initialize them
	 *
	 * @return void
	 */
	setup: function ()
	{
		match_class = new RegExp("^(.*)\s?tooltip\s?(.*)$", 'i');
		match_for = new RegExp("^.*\s?for_(.*)\s?.*$", 'i');
		var divs = document.getElementsByTagName('div');
		var for_result;
		if (divs.length > 0) {
            // Automatically register the mouseout event if followMouse = true and autoHideTimeout is being used
            if (Tooltip.autoFollowMouse && Tooltip.autoHideTimeout) {
                Tooltip.hideEvent[Tooltip.hideEvent.length] = "mouseout";
            }

			if (Tooltip.autoHideClick) {
				Tooltip._attachEvent(document.getElementsByTagName("body").item(0), "clickanywhere");
			}

			for (var i = 0; i < divs.length; i++) {
				if (divs.item(i).className.match(match_class)) {
					for_result = divs.item(i).className.match(match_for);
					if (for_result && for_result.length > 0) {
						if (document.getElementById(for_result[1])) {
							var activator = document.getElementById(for_result[1]);
						}
					} else {
						var foundPrevious = false;
						var activator = divs.item(i);
						while (foundPrevious == false) {
							activator = activator.previousSibling;
							if (activator.tagName) {
								foundPrevious = true;
								break;
							}
						}
					}
					activator.Tooltip = divs.item(i);
					// Just in case you need to access the activator from the Tooltip (i.e. a "Close" button)
					if (!activator.id) {
						activator.id = "tt" + i;
					}
					activator.Tooltip.activator = activator.id ;
	  				Tooltip.init(activator);
				}
			}
		}
	},


	/**
	 * Initiate an Activator/Tooltip for events and display
	 *
	 * @param activator DomElement The element to which the Tooltip show/hide events are attached
	 * @return void
	 */
	init: function (activator)
	{
		var tooltip = activator.Tooltip;
		activator.Tooltip.style.visibility = "hidden";
		activator.Tooltip.style.display = "none";

		Tooltip._attachEvent(activator, "toggle");


		// Remove Link Hrefs
		if (activator.tagName.toLowerCase() == "a") {
			try {
				activator.removeAttribute("href");
				activator.style.cursor = (document.links[0].style.cursor.length > 0) ? document.links[0].style.cursor : "pointer";
			}
			catch (e) {
				//DEBUG alert(e.message);
			}
		}

        // Make sure the Tooltip is on top, only works if the element has position: absolute; in the CSS
        tooltip.style.zIndex = "1000";

		if (Tooltip.autoFollowMouse != true) {
			// Create the <p><a href="#">Close</a></p> and add it to the Tooltip

			// <p> element
			var p = document.createElement('p');

			// <p> styles
			p.style.textAlign = "right";
			p.style.padding.padding = "0";
			p.style.margin = "0";

			// <p> class name
			p.className = "close";

			// <a> element
			var link = document.createElement('a');

			// Set the Tooltip var to the tooltip element
			link.Tooltip = tooltip;

			link.style.cursor = "pointer";

			// Add the click handler
			Tooltip._attachEvent(link, "click");

			// "Close" text node
			var close = document.createTextNode(Tooltip.closeText);

			// Append the text to the <a> element
			link.appendChild(close);

			// Append the <a> to the <p> element
			p.appendChild(link);

			// Stick the entire thing on the end of the Tooltip
			tooltip.appendChild(p, tooltip.firstChild);
		}
	},

	/**
	 * Manually add a Tooltip
	 *
	 * When passed an Activator and Tooltip element or ID, it is setup as a Tooltip
	 *
	 * @param activator Activator Element or ID, this is the element that activates the Tooltip
	 * @param tooltip Tooltip Element or ID, this is the Tooltip element itself that is shown/hidden
	 */
	add: function (activator, tooltip)
	{
		if (typeof activator == 'string') {
			activator = document.getElementById(activator);
		}
		if (typeof tooltip == 'string') {
			tooltip = document.getElementById(tooltip);
		}

		activator.Tooltip = tooltip;
		Tooltip.init(activator);
	},

	/**
	 * Toggle the Tooltip
         *
         * Shows or Hides the Tooltip
         *
         * @param activator Activator Element
         * @return void
	 */

	toggle: function (activator, event)
	{
		try {
			if (activator == 1) {
				activator = document.getElementById(window._currentTT);
			}
		}
		catch (e) { }

		if (Tooltip.autoHideClick && event.type == "click") {
			var close_class = new RegExp("^(.*)\s?close\s?(.*)$", 'i');
			var tooltip_class = new RegExp("^(.*)\s?tooltip\s?(.*)$", 'i');
			if (event.srcElement) {
				var node = event.srcElement;
			} else if (event.fromElement) {
				var node = event.fromElement;
			} else if (event.target) {
				var node = event.target;
			}
			if (node.className == null  || !node.className.match(close_class)) {
				var isWithinTooltip = false;
				while (!isWithinTooltip && node.parentNode) {
					// Check if the parent is a close element first, if so, we can break
					// and we still want to close the tooltip
					if (node.className && node.className.match(close_class)) {
						break;
					}
					if (node.className && node.className != null && node.className.match(tooltip_class)) {
						isWithinTooltip = true;
						break;
					}
					node = node.parentNode;
				}
			}

			if (isWithinTooltip) {
				return;
			}
		}

		try {
			if (activator.Tooltip.isVisible) {
				Tooltip._hide(activator, event);
			} else {
				Tooltip._show(activator, event);
			}
		}
		catch (e) {
			try {
				Tooltip._hide(activator, event);
			}
			catch (e) { }
		}
		event.cancelBubble = true;
		try {
			event.stopPropagation();
		}
		catch (e) { }
	},

	/**
	 * Show the Tooltip
	 *
	 * Displays the Tooltip and sets the hide events up. You should never need to call this manually.
	 *
	 * @param activator Activator Element
    * @private
	 * @return void
	 */
	_show: function (activator, event, ignore_event)
	{
		if (Tooltip.autoHideClick && window._currentTT) {
			Tooltip._hide(document.getElementById(window._currentTT), event, true);
		}

		window._currentTT = activator.id;

		if (ignore_event == true || typeof Tooltip.showEvent == "string" || Tooltip.showEvent.constructor && Tooltip.showEvent.constructor == Array && Tooltip.showEvent.contains(event.type)) {
			activator.Tooltip.isVisible = true;
         if (Tooltip.autoFollowMouse || Tooltip.autoMoveToCursor) {
            Tooltip._follow(activator, event);
         }
			try {
				if (typeof Effect) {
					Element.setOpacity(activator.Tooltip, 0.1);
					activator.Tooltip.style.visibility = "visible";
					activator.Tooltip.style.dispaly = "";					
					
					Tooltip.showMethod(activator.Tooltip, {duration:Tooltip.fade});
				} else {
					activator.Tooltip.style.visibility = "visible";
					activator.Tooltip.style.dispaly = "";										
				}
			}
			catch (e) {
				try {
					activator.Tooltip.style.visibility = "visible";
					activator.Tooltip.style.dispaly = "";										
				}
				catch (e) {
					//DEBUG alert(tooltip.id);
				}
			}
            if (Tooltip.autoFollowMouse) {
                Tooltip._attachEvent(activator, "follow");
            }

            if (Tooltip.autoHideTimeout && !Tooltip.autoFollowMouse) {
                activator.timer = setTimeout(function () {
                                            try {
                                                Tooltip.hideMethod(activator.Tooltip, {duration:Tooltip.fade});
                                            }
                                            catch (e) {
                               					activator.Tooltip.style.dispaly = "none";					
                                                activator.Tooltip.style.visibility = "hidden"; }
                                            }, Tooltip.autoHideTimeout * 1000);
            }

			return;
		}
	},

	/**
	 * Hide the Tooltip
	 *
	 * Hides the Tooltip and sets the show events up. You should never need to call this manually.
	 *
	 * @param activator Activator Element
         * @private
	 * @return void
	 */
	_hide: function (activator, event, ignore_event)
	{
		if (!activator) {
			return;
		}

		event = event.type;

		var tooltip = activator.Tooltip;
        // We need to defer this
        if (event == "mouseout" && Tooltip.autoFollowMouse) {
            activator.timer = setTimeout(function () {
                                            try {
                                                Tooltip.hideMethod(tooltip, {duration:Tooltip.fade});
                                            }
                                            catch (e) {
												activator.Tooltip.style.dispaly = "none";
                                                activator.Tooltip.style.visibility = "hidden"; }
                                            }, Tooltip.autoHideTimeout * 500);
        } else if (ignore_event == true || ((typeof Tooltip.hideEvent == "string" && Tooltip.hideEvent == event) || Tooltip.hideEvent.constructor && Tooltip.hideEvent.constructor == Array && Tooltip.hideEvent.contains(event))) {
			activator.Tooltip.isVisible = false;
			try {
				Tooltip.hideMethod(tooltip, {duration:Tooltip.fade});
			}
			catch (e) {
				activator.Tooltip.style.visibility = "hidden";
				activator.Tooltip.style.dispaly = "none";
			}

			if (Tooltip.autoFollowMouse) {
				Tooltip._removeEvent(activator, "follow");
			}

			window._currentTT = false;

			return;
		}
	},

    _follow: function (activator, event)
    {
      if (activator.timer) {
	      try {
	         clearTimeout(activator.timer);
         }
         catch (e) { }
      }

		var winWidth, winHeight, d=document;
		if (typeof window.innerWidth!='undefined') {
			winWidth = window.innerWidth;
			winHeight = window.innerHeight;
		} else {
			if (d.documentElement && typeof d.documentElement.clientWidth!='undefined' && d.documentElement.clientWidth!=0) {
				winWidth = d.documentElement.clientWidth
				winHeight = d.documentElement.clientHeight
			} else {
				if (d.body && typeof d.body.clientWidth!='undefined') {
					winWidth = d.body.clientWidth
					winHeight = d.body.clientHeight
				}
			}
		}

		var tooltipWidth, tooltipHeight;
		if (activator.Tooltip.currentStyle) {

			tooltipWidth = parseInt(activator.Tooltip.currentStyle.width);
			tooltipHeight = activator.Tooltip.currentStyle.height;
		} else if (window.getComputedStyle) {

			tooltipWidth = parseInt(window.getComputedStyle(activator.Tooltip, null).width);
			tooltipHeight = window.getComputedStyle(activator.Tooltip, null).height;
		}
		activator.Tooltip.style.position = "absolute";

		// filefox
		if (event.pageY) {
			var tmpHeight = parseInt(tooltipHeight);
			if(!isNaN(tmpHeight)){
				var top = event.clientY + document.documentElement.scrollTop - parseInt(tooltipHeight);
			}else{
				var top = event.clientY;
			}
			var left = event.pageX;
		} else if (event.clientY) {

			if ( document.body.scrollTop > document.documentElement.scrollTop){
				top = event.clientY + document.body.scrollTop ;
			}else{
				var tmpHeight = parseInt(tooltipHeight);
				if(!isNaN(tmpHeight)){
					top = event.clientY + document.documentElement.scrollTop - parseInt(tooltipHeight);
				}else{
					top = event.clientY + document.documentElement.scrollTop;
				}
			}

			if (document.body.scrollLeft > document.documentElement.scrollLeft) {
				var left = event.clientX + document.body.scrollLeft + 5;
			} else {
				var left = event.clientX + document.documentElement.scrollLeft - 5;
			}
		}
		// 윈도우 창에 따라 넓이
		if ((left + parseInt(tooltipWidth)) > winWidth) {
			left = left - tooltipWidth;
		}
		
		// 윈도우 창에 따라 높이
//		if ((top - parseInt(tooltipHeight)) > winHeight) {
//			top = top - parseInt(tooltipHeight);
//		}
		
		activator.Tooltip.style.top = top + "px";
		activator.Tooltip.style.left = left + "px";
    },

	/**
	 * Attach show/hide/load events
	 *
	 * This method removes any existing events first
	 * in case show/hide are the same.
	 *
	 * @param element Element to which events should be attached
	 * @param event Event for which events are being registered. One of show/hide/load/click.
	 */

	_attachEvent: function (element, event)
	{
		var i;
		var events = new Array();
        if (event == "toggle") {
			if (Tooltip.showEvent.constructor && Tooltip.showEvent.constructor == Array) {
                for (i = 0; i < Tooltip.showEvent.length; i++) {
                    events.push(Tooltip.showEvent[i]);
                    if (element.addEventListener) {
                        element.addEventListener(Tooltip.showEvent[i], function (e) { Tooltip.toggle(element, e, false); return false; }, false);
                    } else if (element.attachEvent) {
                        element.attachEvent('on' + Tooltip.showEvent[i], function (e) { Tooltip.toggle(element, e, false); return false; });
                    }
                }
            } else {
                events.push(Tooltip.showEvent);
                if (element.addEventListener) {
                    element.addEventListener(Tooltip.showEvent, function (e) { Tooltip.toggle(element, e, false); return false; }, false);
                } else if (element.attachEvent) {
                    element.attachEvent('on' + Tooltip.showEvent, function (e) { Tooltip.toggle(element, e, false); return false; });
                }
            }

            if (Tooltip.hideEvent.constructor && Tooltip.hideEvent.constructor == Array) {
                for (i = 0; i < Tooltip.hideEvent.length; i++) {
                    if (!events.contains(Tooltip.hideEvent[i])) {
                        events.push(Tooltip.hideEvent[i]);
                        if (element.addEventListener) {
                            element.addEventListener(Tooltip.hideEvent[i], function (e) { Tooltip.toggle(element, e, false); return false; }, false);
                        } else if (element.attachEvent) {
                            element.attachEvent('on' + Tooltip.hideEvent[i], function (e) { Tooltip.toggle(element, e, false); return false; });
                        }
                    }
                }
            } else {
                if (!events.contains(Tooltip.hideEvent)) {
                    events.push(Tooltip.hideEvent);
                    if (element.addEventListener) {
                        element.addEventListener(Tooltip.hideEvent, function (e) { Tooltip.toggle(element, e, false); return false; }, false);
                    } else if (element.attachEvent) {
                        element.attachEvent('on' + Tooltip.hideEvent, function (e) { Tooltip.toggle(element, e, false); return false; });
                    }
                }
            }
        } else if (event == "load") {
            if (element.addEventListener) {
                element.addEventListener("load", function () { Tooltip.setup(); }, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + "load", function () { Tooltip.setup(); });
            }
        } else if (event == "click") {
            if (element.addEventListener) {
                element.addEventListener("click", function (e) { Tooltip.toggle(element, e, true); }, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + "click", function (e) { Tooltip.toggle(element, e, true); });
            }
        } else if (event == "follow") {
            if (element.addEventListener) {
                element.addEventListener("mousemove", function (e) { Tooltip._follow(element, e); }, false);
            }  else {
                element.attachEvent('onmousemove', function (e) { Tooltip._follow(element, e);  });
            }
        } else if (event == "clickanywhere") {
			if (element.addEventListener) {
                element.addEventListener("click", function (e) { Tooltip.toggle(Tooltip.CURRENT_TOOLTIP, e, false); }, false);
            }  else {
                element.attachEvent('onclick', function (e) { Tooltip.toggle(Tooltip.CURRENT_TOOLTIP, e, false);  });
            }
		}
	},

    _removeEvent: function (element, event)
    {
        try {
            if (event == "follow") {
                if (element.addEventListener) {
                    element.removeEventListener("mousemove", function (e) { Tooltip._follow(element, e); }, false);
                } else {
                    element.dettachEvent('onmousemove', function (e) { Tooltip._follow(element, e); });
                }
            }
        }
        catch (e) {}
    }
}

// Start the Tooltips in motion
try {
	Tooltip._attachEvent(window, 'load');
}
catch (e) { }
var Drag={"scrollPos":null,"obj":null,"init":function(a,aRoot,ee){if(ee==null){a.onmousedown=Drag.start;}
a.root=aRoot;if(isNaN(parseInt(a.root.style.left)))a.root.style.left="0px";if(isNaN(parseInt(a.root.style.top)))a.root.style.top="0px";a.root.onDragStart=new Function();a.root.onDragEnd=new Function();a.root.onDrag=new Function();if(ee!=null){var b=Drag.obj=a;ee=Drag.fixE(ee);var c=parseInt(b.root.style.top);var d=parseInt(b.root.style.left);b.root.onDragStart(d,c,ee.clientX,ee.clientY);b.lastMouseX=ee.clientX;b.lastMouseY=ee.clientY;document.onmousemove=Drag.drag;document.onmouseup=Drag.end;}},"start":function(a){var b=Drag.obj=this;a=Drag.fixE(a);var c=parseInt(b.root.style.top);var d=parseInt(b.root.style.left);b.root.onDragStart(d,c,a.clientX,a.clientY);b.lastMouseX=a.clientX;b.lastMouseY=a.clientY;document.onmousemove=Drag.drag;document.onmouseup=Drag.end;Drag.scrollPos=Drag.scrollsPos();return false;},"drag":function(a){a=Drag.fixE(a);var b=Drag.obj;var c=a.clientY;var d=a.clientX;var e=parseInt(b.root.style.top);var f=parseInt(b.root.style.left);var h,g;h=f+d-b.lastMouseX;g=e+c-b.lastMouseY;var p=Drag.scrollsPos();g-=Drag.scrollPos-p;Drag.scrollPos=p;b.root.style.left=h+"px";b.root.style.top=g+"px";b.lastMouseX=d;b.lastMouseY=c;b.root.onDrag(h,g,a.clientX,a.clientY);return false;},"end":function(){document.onmousemove=null;document.onmouseup=null;Drag.obj.root.onDragEnd(parseInt(Drag.obj.root.style.left),parseInt(Drag.obj.root.style.top));Drag.obj=null;},"fixE":function(a){if(typeof a=="undefined")a=window.event;if(typeof a.layerX=="undefined")a.layerX=a.offsetX;if(typeof a.layerY=="undefined")a.layerY=a.offsetY;return a;},
"scrollsPos":function(){if(BrowserInfo.isIE||BrowserInfo.isOpera){if(document.body.scrollTop){return document.body.scrollTop;}else{return document.documentElement.scrollTop;}}else if(BrowserInfo.isFirefox){return window.pageYOffset;}return 0;}};var Window = Class.create();
Window.prototype = {
	initialize: function(id) {
		if(id == undefined) id= "common_dialog";
		
		this.options = Object.extend({
			className:       "alertbox",
			parent:           document.getElementsByTagName("body").item(0),
			url:                 null,
			width:             500,
			height:            700
			}, arguments[1] || {});
					
		this.element = this._createWindow(id);
		this.setSize(this.options.width, this.options.height);
	},

	getContent: function () {
		return $(this.element.id + "_content");
	},
	
	_createWindow: function(id) {
		var className = this.options.className;
		win = document.createElement("div");
		win.setAttribute('id', id);
		win.className = className;
		if (this.options.url){
			closeDiv="<div><a href='#' onclick='hideLayer()' STYLE='width:20px;height:20px;position:absolute;top:5px;left:676px;'></a></div>";
			var content= "<IFRAME name=\"" + id + "_content\"  id=\"" + id + "_content\" SRC=\"" + this.options.url + "\" scrolling=\"no\"  frameborder=\"0\"  marginwidth=\"0\" marginheight=\"0\" ></IFRAME>";
			win.innerHTML = 	closeDiv + content;
		}	else{
			var content ="<DIV name=\"" + id + "_content\"  id=\"" + id + "_content\" ></DIV>";
			win.innerHTML =	content;
		}
		this.options.parent.insertBefore(win, this.options.parent.firstChild);
		return win;
	},

	// Sets window size
	setSize: function(width, height) {
		this.width = parseFloat(width);
		this.height = parseFloat(height);
		var left = this.width;
		var top = this.height;
		Element.setStyle(this.element, {width: left, height:top});
		var content = this.	getContent();
		Element.setStyle(content, {width: this.width+"px", height:this.height+"px"});
	},
	showCenter: function() {
		this._center();
		WindowUtilities.disableScreen(this.options.className);
		zIndex = WindowUtilities.maxZIndex + 20;
		this.element.setStyle({zIndex: zIndex});
		WindowUtilities.updateZindex(zIndex, this);
		Element.show(this.element);
	},
	_center: function() {
		var windowScroll = WindowUtilities.getWindowScroll();
		var pageSize = WindowUtilities.getPageSize();
		Dialog.PageSize = pageSize;
		var top = windowScroll.top + (pageSize.windowHeight - (this.height))/2;
		var left = windowScroll.left + (pageSize.windowWidth - (this.width))/2;
		this.element.setStyle({top: top + 'px', left : left + 'px' });
//		win.focus(); win.blur();
	}
};

var Dialog = {
	PageSize : null,
	checkAlertTime: 500,
 	win: null,
	
	alert: function(message, parameters, check, setTime) {
		parameters = parameters || {};
		var windowParam = parameters.windowParameters || {};
		windowParam.className = windowParam.className || "alertbox";
		windowParam.btnValue = windowParam.btnValue || "확인";		
		var content = '<div class="alertbox"> \
								<div class="alertbox-top"></div>\
								<div class="alertbox-middle">\
									<div class="alertbox-middle-msg">\
										<span> '+message+'</span>\
									</div>';
									if(check != "N") {
										content = content + '<div class="alertbox-middle-action"><input type="button" class="alertbox-button" value="'+ windowParam.btnValue +'"  onclick="Dialog.okCallback()" /></div>';
									}
								content = content + '</div>\
								<div class="alertbox-bottom"></div>\
							</div>';
		if(setTime=="Y") {
			window.setTimeout(okCloseLayer, this.checkAlertTime);		
		}
		var result = this._openDialog(content, parameters);
		this.eventKeyDown = this.keyAction.bindAsEventListener(this);
		Event.observe(document, "keydown", this.eventKeyDown);
		return result;
	},

	checkalert: function(message, parameters) {
		this.alert(message, parameters, "N", "Y");
	},	
	conFirm : function(field, parameters){
		parameters = {className: "alertbox-container", width:280, height:145};
		parameters = parameters || {};
		var windowParam = parameters.windowParameters || {};
		windowParam.className = windowParam.className || "alertbox";
		var content = '<div class="alertbox"> \
			<div class="alertbox-top"></div>\
			<div class="alertbox-middle">\
				<div class="alertbox-middle-msg">\
					<span>정말로 게시물을 삭제하시겠습니까?</span>\
				</div>\
				<div class="alertbox-middle-action"><input type="button" class="alertbox-button" value="확인"/><input type="button" class="alertbox-button" value="취소" onclick="Dialog.okCallback()"  /></div>\
			</div>\
			<div class="alertbox-bottom"></div>\
		</div>';
		return this._openDialog(content, parameters);
	},
	// iframe url
	iframe: function(parameters) {
		parameters = parameters || {};
		var content = null;
		return this._openDialog(content, parameters);
	},

	html: function(obj, parameters) {
		parameters = parameters || {};
		var windowParam = parameters.windowParameters || {};
		windowParam.className = windowParam.className || "alertbox";
		var content = obj.innerHTML;
		return this._openDialog(content, parameters);
	},
	
	// html
	htmlLayer : function(obj,szClassName){

		//템플릿 상세보기 레이어의 면적
		if(szClassName == 'layer-template-detail') {
			nWidth=700;
			nHeight=569;
		}else{
			//스킨 상세보기 레이어의 면적
			nWidth=748;
			nHeight=293;
		}
		this.html(obj, {windowParameters: {className: szClassName, width:nWidth, height:nHeight}});	
	},	
	
	//message
	message : function(msg){
		this.alert(msg, {windowParameters: {className: "alertbox-container", width:280, height:145}});	
	},
	
	message2 : function(msg){
		this.checkalert(msg, {windowParameters: {className: "alertbox2-container", width:280, height:145}});	
	},
	
	// 실명인증
	nameAuth: function(parameters , authInfo) {
		parameters = parameters || {};
		// HTML
		var content = '<form name="authForm" id="authForm" method=post ><div class="memberbox memberbox-realname"> \
		<div class="memberbox-top "> \
			<h1 class="memberbox-h"><a href="#//">실명 확인</a></h1> \
			<div class="btn-close"><a href="#//" onclick="Dialog.okCallback()" >닫기</a></div> \
		</div> \
		<div class="memberbox-middle"> \
			<div class="memberbox-contents"> \
				<div class="memberbox-info-tit"> \
					<h2 class="memberbox-h">실명 확인이 필요한 서비스입니다.</h2><span>정확한 실명과 주민등록번호를 입력해주세요.</span> \
				</div> \
				<h3 class="memberbox-h">실명 확인</h3> \
				<div class="memberbox-realname-container"> \
					<div class="memberbox-realname-control">\
						<div class="memberbox-realname-input"><label class="memberbox-realname-input-name" for="u_name">이름</label><input type="text" id="u_name" name="u_name" value="" /></div>\
						<div class="memberbox-realname-input">\
							<label class="memberbox-realname-input-idcode" for="resident_num1">주민등록번호</label><input type="text" id="resident_num1" name="resident_num1" value="" onKeyUp="check_number(this);" maxlength="6" /><span>-</span><input type="password" id="resident_num2" name="resident_num2" value="" onKeyUp="check_number(this);" maxlength="7" onkeydown=\'if(event.keyCode == 13 ){ if(this.value!=""){ajax.arraypost("nameAuth:'+parameters.authInfo.uri+':authForm:post:'+parameters.authInfo.query+':auth_msg:none"); }}\' />\
						</div>\
						<div class="memberbox-btn-confirm01"><a href="#//" ajax="nameAuth:'+parameters.authInfo.uri+':authForm:post:'+parameters.authInfo.query+':auth_msg:none" >확인</a></div>\
					</div>\
					<div id="auth_msg" name="auth_msg" class="memberbox-realname-alert-discord"></div>\
					<div class="memberbox-realname-info">\
						<div class="memberbox-lock-notice">명의도용방지 서비스를 사용하고 계신 분께서는 차단기능을 일시해제하고 실명 확인을 해주시기 바랍니다.</div>\
						<div class="memberbox-realname-info-method">정확한 이름과 주민등록번호를 입력하셨나요? <br />실명 확인 서비스는 서울신용평가정보의 신용정보 DB를 통해 제공되고 있습니다.<br />서울신용평가정보 DB에 개인정보가 제대로 등록되어 있지 않은 경우, 실명 확인이 되지 않을 수 있습니다.<br />이 경우 <span>본인의 신분증 사본(주민등록증/여권/운전면허증)과 연락 가능한 전화번호를 적으셔서 <br />FAX 또는 E-Mail 로 </span>보내주시면 실명확인을 하실 수 있습니다.	\
						</div>\
						<div class="memberbox-realname-info-address">\
							<strong>FAX:</strong> 02-3449-1678<br />\
							<strong>E-Mail:</strong> credit@siren24.com	\
						</div>\
					</div>\
				</div>\
				<div class="memberbox-realname-notice">실명 확인은 서울신용평가정보의 신용DB를 근거로 확인하게 되며 실명 확인 외의 다른 목적으로 절대 이용되지 않습니다.</div>\
			</div><!--memberbox-contents-->\
		</div><!--memberbox-middle-->\
		<div class="memberbox-bottom"></div>\
		</div></form>';
		// make 
		var win = this._openDialog(content, parameters);
		try{ajax._parser();}catch(e){}
		return win ;
	},	
	
	// common 공통 Dialog
	_openDialog: function(content, parameters) {
		var common_id = "common_dialog";
		var windowParam = parameters && parameters.windowParameters ? parameters.windowParameters : {};
		this.win = new Window(common_id, windowParam);
		if( content != null){
			this.win.getContent().innerHTML = content;
		}
		this.win.showCenter();
		this.eventResize = this.recenter.bindAsEventListener(this);
		Event.observe(window, "resize", this.eventResize);
		Event.observe(window, "scroll", this.eventResize);
		hideSelectBoxes();
		return this.win;
	},	
	okCallback: function() {
		Event.stopObserving(window, "resize", this.eventResize);
		Event.stopObserving(window, "scroll", this.eventResize);
		if(this.eventKeyDown != undefined){
			Event.stopObserving(document, "keydown", this.eventKeyDown);
		}
	    showSelectBoxes();
		WindowUtilities.enableScreen();
	},
	
	recenter: function() {
		this.win._center();
	},	
	 getKeyCode : function(event){
	     if(!event)  event = window.event;
	     if(event.which)
	     	var keycode = event.which;
	     else
	     	var keycode = event.keyCode;
	     return keycode;
	},

 	keyAction :function(event){
	 	 keyCode = this.getKeyCode(event);
	 	// 32 : spacebar, 13 : enter, 27 : ESC
    	if(keyCode == 13 || keyCode == 32 || keyCode == 27){
    		this.okCallback();
    	}
    	return false;
	}
}

var WindowUtilities = {
	maxZIndex: 100,
	
	updateZindex: function(zindex, win) {
		if (zindex > this.maxZIndex) {
			this.maxZIndex = zindex;
		}
	},
	getWindowScroll: function() {
		return { top: BrowserInfo.getScrollTop(), left: BrowserInfo.getScrollLeft()};
	},
	getPageSize: function(){
		return {pageWidth: BrowserInfo.getDocumentWidth() ,pageHeight: BrowserInfo.getDocumentHeight() , 
					windowWidth: BrowserInfo.getClientWidth(), windowHeight: BrowserInfo.getClientHeight()};
	},
 	disableScreen: function(className, id) {
		id = id || 'overlay_modal';
		this.initOverlay(id, className);
	 	var objOverlay = $(id);
		var  pageSize = Dialog.PageSize;
		objOverlay.style.height = (pageSize.pageHeight + 'px');
		objOverlay.style.display = '';
	},
 	enableScreen: function(id) {
 	  	id = id || 'overlay_modal'
	 	var objDialog =  $('common_dialog');
		if (objDialog) {
			objDialog.style.display = 'none';
			objDialog.parentNode.removeChild(objDialog);
		}
	 	var objOverlay =  $(id);
		if (objOverlay) {
			objOverlay.style.display = 'none';
			objOverlay.parentNode.removeChild(objOverlay);
		}
	},
	
	// initOverlay();
	initOverlay: function(id, className) {
		if ($(id)) {
			Element.setStyle(id, {zIndex: WindowUtilities.maxZIndex + 10});
		}else {
			var objBody = document.getElementsByTagName("body").item(0);
			var objOverlay = document.createElement("div");
			objOverlay.setAttribute('id', id);
			objOverlay.className = "overlay_" + className;
			with (objOverlay.style) {position = 'absolute';	display = 'none';	top = '0'; left = '0'; zIndex = WindowUtilities.maxZIndex + 10; width = '100%';}
			objBody.insertBefore(objOverlay, objBody.firstChild);
		}
	}

}