/*
 *  공용 스크립트
 *  Developed by: ofdream
 *  Powered by: ofdream.com
 *  License: 개인용도
 *  
 *  Open Source References :
 *  + 참고소스 : 
 *  + 참고소스 : 
 *  + 참고소스 : 
 */

var isIE = navigator.userAgent.indexOf("MSIE") > -1;
var isChrome = navigator.userAgent.indexOf("Chrome") > -1;
var isFirefox = navigator.userAgent.indexOf("Firefox") > -1;

/*
if(navigator.userAgent.indexOf("MSIE 8.0") > 0 ){
 document.write("IE8")
}
else if(navigator.userAgent.indexOf("MSIE 7.0") > 0 ){
 document.write("IE7")
}
else if(navigator.userAgent.indexOf("MSIE 6.0") > 0 ){
 document.write("IE6")
}
else if(navigator.userAgent.indexOf("Firefox") > 0 ){
 document.write("Firefox")
}
else if(navigator.userAgent.indexOf("Safari") > 0 ){
 document.write("Safari")
}
else if(navigator.userAgent.indexOf("Chrome") > 0 ){
 document.write("Chrome")
}
*/


if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement)
{
	HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode)
	{
		switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
			else this.parentNode.appendChild(parsedNode);
			break;
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr)
	{
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
	}

	HTMLElement.prototype.insertAdjacentText = function(where,txtStr)
	{
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
	}
}

//문자열의 바이트수를 리턴
function ByteCount(strText) 
{ 
    var nByte = 0; 
    for(var i=0; i<strText.length; i++) 
    { 
        nByte += (strText.charCodeAt(i)>128) ? 2 : 1; 
    } 
    return nByte; 
} 

//문자열이 숫자인지 확인
function isNumber(s) {
  s += ''; // 문자열로 변환
  s = s.replace(/^\s*|\s*$/g, ''); // 좌우 공백 제거
  if (s == '' || isNaN(s)) return false;
  return true;
}

//아이디 특수문자 확인
function CheckIDString(strText) 
{ 
	var regexp = /[^a-zA-Z0-9]/; 

    var result = !regexp.test(strText); 
    return result;
} 

//날짜 유효성 검사 (이거 약간 이상함. )
function isValidDate(iDate) {
  if( iDate.length != 8 ) {
    return false;
  }
  
  oDate = new Date();
  oDate.setFullYear(iDate.substring(0, 4));
  oDate.setMonth(parseInt(iDate.substring(4, 6)) - 1);
  oDate.setDate(iDate.substring(6));

  if( oDate.getFullYear()     != iDate.substring(0, 4)
      || oDate.getMonth() + 1 != iDate.substring(4, 6)
      || oDate.getDate()      != iDate.substring(6) ){
    
    return false;
  }
   
  return true;
}

// 문자열 변환
function replaceString(str, from, to)
{
	var index;
	var pstr;
	var str1;
	var str2;
	if((index = str.indexOf(from)) >= 0) {
	str1 = str.substr(0, index);
	str2 = str.substr(index+(from.length), str.length);
	pstr = str1;
	pstr += to;
		if(str2 && str2.length >= from.length) {
	   pstr += replaceString(str2, from, to);
		}
		return pstr;
	}else{
		return str;
	}
}

function htmlToText(str)
{

	str = replaceString(str, "&", "&amp;");
	str = replaceString(str, " ", "&nbsp;");
	str = replaceString(str, "\t", "&nbsp;&nbsp;&nbsp; ");
	str = replaceString(str, "\"", "&quot;");
	str = replaceString(str, "<", "&lt;");
	str = replaceString(str, ">", "&gt;");

	str = replaceString(str, "&nbsp;&nbsp;", "&nbsp; ");	
	return str;
}


function setCookie( name, value, expiredays ) 
{ 
    var todayDate = new Date(); 
    todayDate.setDate( todayDate.getDate() + expiredays ); 
    document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";" 
} 

function getCookie(name) {
	var 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));
}


function deleteCookie(CookieName)
{
	var tmp = getCookie(CookieName);
	if(tmp) 
	{ 
		setCookie(CookieName,tmp,(new Date(1))); //Used for Expire 
	}
}


//이 쿠키함수가 새로 만든거. 
/*  쿠키값 넣기 */
function _setCookie(name,value){
	var argc = _setCookie.arguments.length;
	var argv = _setCookie.arguments;

	/*
	var expires = (argc>2)?argv[2]:null;
	var path = (argc>3)?argv[3]:null;
	var domain = (argc>4)?argv[4]:null;
	var secure = (argc>5)?argv[5]:false;
	*/

	var cur_domain = document.domain;
	var arr  = cur_domain.split("."); 
	var cookie_domain = "";
	if( arr[0] == "www" )
	{
		for(i=1; i<arr.length; i++)
		{
			cookie_domain += "." + arr[i];
		}
	}
	else
	{
		cookie_domain = "." + cur_domain;
	}

	// 기본값을 설정해준다.
	var expires = (argc>2) ? argv[2] : null;
	var path = (argc>3) ? argv[3] : "/";
	var domain = (argc>4) ? argv[4] : cookie_domain;//".ofdream.com";	
	var secure = (argc>5) ? argv[5] : false;

	document.cookie = name + "=" + escape(value) +
		((expires==null)?"":(";expires=" + expires.toGMTString())) +
		((path==null)?"":(";path=" + path)) +
		((domain==null)?"":(";domain=" + domain)) +
		((secure==true)?";secure":"");
}

/* 쿠키값 가져오기 */
function _getCookie(name){
	var find_flag = false;
	var start,end;
	var i = 0;
	while(i<document.cookie.length){
		start = i;
		end = start + name.length
		if (document.cookie.substring(start,end) == name){
			find_flag = true;
			break;
		}
		i++;
	}
	if (find_flag == true){
		start = end + 1;
		end = document.cookie.indexOf(";",start);
		if (end<start) end = document.cookie.length;
		return document.cookie.substring(start,end);
	}
	return "";
}


/* 쿠키값 삭제하기 */
function _deleteCookie(name){
	var today = new Date();
	today.setTime(today.getTime()-1);
	var value = _getCookie(name);
	if (value != "")
		document.cookie = name + "=" + value + "; expires=" + today.toGMTString();
}



function isSSN(s1, s2) {
  n = 2;
  sum = 0;
  for (i=0; i<s1.length; i++)
    sum += parseInt(s1.substr(i, 1)) * n++;
  for (i=0; i<s2.length-1; i++) {
    sum += parseInt(s2.substr(i, 1)) * n++;
    if (n == 10) n = 2;
  }
 
  c = 11 - sum % 11;
  if (c == 11) c = 1;
  if (c == 10) c = 0;
  if (c != parseInt(s2.substr(6, 1))) return false;
  else return true;
}

//입력문자에 따라 다음 입력란으로 자동 이동	
function nextElement(obj, num, obj_)
{
	if( obj.value.length == num )
	{
		obj_.focus();
	}
}	

/*
특정 오브젝트의 left, top, width height 박스사이즈 구하기
	var box = getBounds(document.getElementById('aaa')); 
	box.left;
	box.top;
	box.width;
	box.height;
*/
function getBounds(tag) 
{ 
	var ret = new Object(); 
	if(tag.getBoundingClientRect) { 
		var rect = tag.getBoundingClientRect(); 
		ret.left = rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft); 
		ret.top =  rect.top + (document.documentElement.scrollTop || document.body.scrollTop); 
		ret.width = rect.right - rect.left; 
		ret.height = rect.bottom - rect.top; 
		ret.right = rect.right;
		ret.bottom = rect.bottom;
	} else { 
		var box = document.getBoxObjectFor(tag); 
		ret.left = box.x; 
		ret.top = box.y; 
		ret.width = box.width; 
		ret.height = box.height; 
		ret.right = box.x + box.width;
		ret.bottom = box.y + box.height;
	} 
	return ret; 
} 

//특정 오브젝트의 left, top 절대값 구하기
function getRealOffsetTop(o) { return o ? o.offsetTop + getRealOffsetTop(o.offsetParent) : 0; } 
function getRealOffsetLeft(o) { return o ? o.offsetLeft + getRealOffsetLeft(o.offsetParent) : 0; } 


function GetObjTop(obj) { 
    if(obj.offsetParent == document.body) return obj.offsetTop; 
    else return obj.offsetTop + GetObjTop(obj.offsetParent); 
} 

function GetObjLeft(obj) { 
    if(obj.offsetParent == document.body) return obj.offsetLeft; 
    else return obj.offsetLeft + GetObjLeft(obj.offsetParent); 
} 

//스크롤 포지션
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

//현재 마우스 좌표 포인터 (스크롤 제외)
function getMousePos(e) 
{ 
	var ret = new Object(); 

	moz=document.getElementById&&!document.all;
	ret.x=(!moz?e.clientX:e.pageX);
	ret.y=(!moz?e.clientY:e.pageY);

	if( moz )
	{
		ret.x -= f_scrollLeft();
		ret.y -= f_scrollTop();
	}

	return ret; 
} 

//현재 마우스 좌표 (스크롤 포함)
function getMouseScrollPos(e) 
{ 
	var ret = new Object(); 

	moz=document.getElementById&&!document.all;
	ret.x=(!moz?e.clientX:e.pageX);
	ret.y=(!moz?e.clientY:e.pageY);

	if( !moz )
	{
		ret.x += f_scrollLeft();
		ret.y += f_scrollTop();
	}

	return ret; 
} 

function getBrowserSize()
{
	var obj = new Object(); 

	var browserWidth = 0, browserHeight = 0;

	if (document.body && document.body.offsetWidth) 
	{
		 obj.width = document.body.offsetWidth;
		 obj.height  = document.body.offsetHeight;
	}
	if (document.compatMode=='CSS1Compat' &&
		document.documentElement &&
		document.documentElement.offsetWidth ) 
	{
		obj.width = document.documentElement.offsetWidth;
		 obj.height = document.documentElement.offsetHeight;
	}
	if (window.innerWidth && window.innerHeight) {
	 obj.width = window.innerWidth;
	 obj.height = window.innerHeight;
	}

	return obj;
}

// get scrolled page size
function getScrollSize()
{
	try
	{
		var db = document.body;
		var dde = document.documentElement;

		var scrollHeight = Math.max(db.scrollHeight, dde.scrollHeight, db.offsetHeight, dde.offsetHeight, db.clientHeight, dde.clientHeight)
		var scrollWidth = Math.max(db.scrollWidth, dde.scrollWidth, db.offsetWidth, dde.offsetWidth, db.clientWidth, dde.clientWidth)

		return {x: scrollWidth, y: scrollHeight};
	}
	catch(e) {}

	return {x: 0, y: 0};
}


// get scrolled page position
function getScrollPos()
{
	try
	{
		if (typeof(pageXOffset) != 'undefined') {return {x: pageXOffset, y: pageYOffset};}  // IE throws an exception if I use "!isDef(pageXOffset)"
		else 
		{
			var db = document.body;
			var dde = document.documentElement;
			return ((dde.clientHeight) ? {x: dde.scrollLeft, y: dde.scrollTop} : {x: db.scrollLeft, y: db.scrollTop});
		}
	}
	catch(e) {}

	return {x: 0, y: 0};
}

//공용 다이얼로그 박스
var g_dlg_id = 0;

function DoCreateDlg(e, strOption) 
{
	//
	var id = "dlg_" + (++g_dlg_id);    

	var position = "center";
	var url = "";
	var left = "100";
	var top = "100";
	var width = "400";
	var height = "300";
	var title = "Dialog";
	var content = "";
	var resize="true";

	var arr;
	arr = strOption.split(",");
	for(i=0; i<arr.length; i++)
	{
		var arr2 = arr[i].split("=");

		if( arr2[1].length > 0 )
		{
			if( arr2[0] == "id" ) id = arr2[1];
			else if( arr2[0] == "position" ) position = arr2[1];
			else if( arr2[0] == "url" ) url = arr2[1];
			else if( arr2[0] == "left" ) left = arr2[1];
			else if( arr2[0] == "top" ) top = arr2[1];
			else if( arr2[0] == "width" ) width = arr2[1];
			else if( arr2[0] == "height" ) height = arr2[1];
			else if( arr2[0] == "title" ) title = arr2[1];
			else if( arr2[0] == "resize" ) resize = arr2[1];
			else if( arr2[0] == "content" ) 
			{
				content = arr[i].replace("content=", "");
			}
		}
	}

	//아이디가 있으면
	var before_dlg = document.getElementById(id);
	if(  before_dlg ) //이미 있으면
	{
		before_dlg.style.display = "block";
		return;
	}

	var objDlg = document.createElement("DIV");
	objDlg.id = id;
	objDlg.className = "dlg_box"; 
	objDlg.zIndex = g_dlg_id;
	objDlg.style.left = left + "px";
	objDlg.style.top = top + "px";
	objDlg.style.width = width + "px";
	objDlg.style.height = height + "px";

	var	tag = "<div  id='move_title_" + id + "' style='width:100%;board:1px #00ff00 solid;height:24px; font-size:14px; font-weight:bold;background:url(/odsys/img/green_header.gif) repeat-x; color:#3c7f51'>"
				tag += "<div style='float:left; margin: 3px 0px 0px 6px;'>" + title + "</div>";
				tag += "<div style='float:right; cursor:pointer; margin: 6px 6px 0px 0px; height:11px; width:11px;'>";
					tag += "<a href='javascript:OnCloseDlg(\"" +  id + "\");' ><img src='/odsys/img/dlg_close.gif' border='0'></a>";
				tag += "</div>";
			tag += "</div>";
			tag += "<div style='z-index:99;'>";
			if( url.length < 1 )
			{
				tag += content;
			}
			else //iframe url
			{
				tag += "<iframe id='_pop_frame' src='" + url + "' scrolling='auto' frameborder='0' style='width:100%;height:100%;overflow:auto;' ></iframe>";  
			}
			tag += "</div>";

	if( resize == "true" )	tag += "<div  id='resize_icon_" + id + "' style=' z-index:100;width:16px;height:16px;left:200px; 	top:200px; position:absolute; background-image:url(/odsys/img/dlg_resize.gif);cursor:nw-resize;'></div>";

	

	objDlg.innerHTML = tag;

	document.body.appendChild(objDlg);

	//동적으로 띄운다.
	objDlg.style.display = "block";

	if( position == "center" )	//중앙정렬 옵션시
	{
		var objBW = getBrowserSize();	//브라우저 사이즈

		//상하좌우 중앙정렬
		var box = getBounds(objDlg);

		targetTop =  (objBW.height / 2) - (box.height / 2) + f_scrollTop();
		targetLeft =  (objBW.width / 2) -  (box.width / 2) + f_scrollLeft();
		
		objDlg.style.top =  targetTop + 'px';
		objDlg.style.left = targetLeft + 'px';
	}
	else if ( position == "mouse" )	//마우스 포인터에 띄위기
	{
		var browserWidth = 0, browserHeight = 0;

		if (document.body && document.body.offsetWidth) 
		{
			 browserWidth = document.body.offsetWidth;
			 browserHeight = document.body.offsetHeight;
		}
		if (document.compatMode=='CSS1Compat' &&
			document.documentElement &&
			document.documentElement.offsetWidth ) 
		{
			browserWidth = document.documentElement.offsetWidth;
			 browserHeight = document.documentElement.offsetHeight;
		}
		if (window.innerWidth && window.innerHeight) {
		 browserWidth = window.innerWidth;
		 browserHeight = window.innerHeight;
		}

		//상하좌우 크기에 맞춰서 정렬
		var box = getBounds(objDlg);
		var mouse = getMousePos(e);

		if( f_scrollTop() + mouse.y + box.height > f_scrollTop() + browserHeight ) 
		{
			mouse.y = mouse.y - ( ( f_scrollTop() + mouse.y + box.height ) - (f_scrollTop() + browserHeight) + 30 ); //12는 하단 스크롤바 감안
		}

		if( f_scrollLeft() + mouse.x + box.width > f_scrollLeft() + browserWidth ) 
		{
			mouse.x = mouse.x - ( ( f_scrollLeft() + mouse.x + box.width ) - (f_scrollLeft() + browserWidth) + 20 ); //12는 하단 스크롤바 감안
		}

		//0,0 좌표 안으로 넘거가는 경우
		if( mouse.y < 0 ) mouse.y = 20;
		if( mouse.x < 0 ) mouse.x = 20;
	
		objDlg.style.top =  (f_scrollTop() + mouse.y) + 'px';
		objDlg.style.left = (f_scrollLeft() + mouse.x) + 'px';
	}

	if( resize == "true" ) // "" 붙여야 한다. 
	{
		var drag1 = new drag();
		drag1.init( {id:"resize_icon_" + id ,direction:"resize"} );
	}

	var drag2 = new drag();
	drag2.init({id:"move_title_" + id,direction:"move"});

//	return false; 
}

function OnCloseDlg(id)
{
	var objDlg = document.getElementById(id);
	if( objDlg )
	{
		objDlg.style.display = "none";
		document.body.removeChild(objDlg);
	}
}

function addEvent ( obj, type, fn ) 
{
	if ( obj.attachEvent ) 
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	} else 
	obj.addEventListener( type, fn, false );
}

function removeEvent ( obj, type, fn ) 
{
	if ( obj.detachEvent ) 
	{
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
	} else
	obj.removeEventListener( type, fn, false );
}

Function.prototype.bind = function(obj) 
{
    var _method = this;
    return function() {
        return _method.apply(obj, arguments);
    };    
}

function drag(id) 
{
	this.id = "id";
	this.direction = "resize";
}

drag.prototype = 
{ 
	init:function(settings) {
	    for(var i in settings){
		    this[i] = settings[i];
		}

		this.elem = (this.id.tagName==undefined) ? document.getElementById(this.id) : this.id;

		this.container = this.elem.parentNode;	
	    this.elem.onmousedown = this._mouseDown.bind(this);			 

		if( this.direction == "resize" )
		{
			var box = getBounds(this.container);
			this.elem.style.left = box.width - 20 + "px";
			this.elem.style.top = box.height - 20 + "px";
		}
	},
	
	_mouseDown: function(e) {
		e = e || window.event;

		this.elem.onselectstart=function(){return false};
		
		this._event_docMouseMove = this._docMouseMove.bind(this);		
		this._event_docMouseUp = this._docMouseUp.bind(this);	
			
	    if (this.onstart) this.onstart();
		this.x = e.clientX||e.PageX;
		this.y = e.clientY||e.PageY;
		
		this.left = parseInt(getstyle(this.elem, "left"));
        this.top = parseInt(getstyle(this.elem, "top"));
        
        addEvent(document, 'mousemove', this._event_docMouseMove);	
 		addEvent(document, 'mouseup', this._event_docMouseUp);
        
		//ofdream
		var box = getBounds(this.container);
		var mouse = getMouseScrollPos(e);

		this.saveLeft = box.left;
		this.saveTop = box.top;
		
		this.saveMarginX = box.left - mouse.x - 1;
		this.saveMarginY = box.top - mouse.y - 11;

		if( isFirefox )	this.saveMarginY = box.top - mouse.y - 10; //FF
		

        return false;	
    },
	 _docMouseMove: function(e) {
	    
		this.setValuesClick(e);	   
		if (this.ondrag) this.ondrag();
    },

	_docMouseUp: function(e) {
	 removeEvent(document, 'mousemove', this._event_docMouseMove);
	if (this.onstop) this.onstop();

	removeEvent(document, 'mouseup', this._event_docMouseUp);
						
	},

	setValuesClick: function(e)
	{ 
		this.mouseX = e.clientX||e.PageX;
		this.mouseY = e.clientY||e.pageY;

		if (this.direction=="resize") 
		{

			this.Y = this.top + this.mouseY - this.y;
			
			this.elem.style.top = this.Y +"px";

			this.X = this.left+ this.mouseX - this.x;	    
		
			this.elem.style.left = this.X+"px";
			this.container.style.width = (this.X + 16) +"px";
			this.container.style.height = (this.Y + 16) +"px";

		}
		else  //"move"
		{
			var mouse = getMouseScrollPos(e);
			newTop = mouse.y + this.saveMarginY ;
			newLeft = mouse.x + this.saveMarginX;

			this.container.style.top = newTop +"px";  
			this.container.style.left = newLeft +"px";  
		}
	}
}

function getstyle(elem, prop) {
		if(document.defaultView)
		{
			return document.defaultView.getComputedStyle(elem, null).getPropertyValue(prop);
		}
		else if(elem.currentStyle)
		{
			var prop = prop.replace(/-(\w)/gi, function($0,$1)
			{
			
				return $1.toUpperCase();
			});
			return elem.currentStyle[prop];
		}
		else return null;
	}


// 사용샘플
/*
function SampleDialog(e) 
{
	var aaa = document.getElementById("login");
	var content = aaa.innerHTML;
	DoCreateDlg(e, 'id=login_dlg,title=안녕하세요,position=mouse,url=,width=400,height=300,top=200,left=200,content=' + content);
	return;
}
*/

// 공용 다이얼로그 박스 //

//썸네일 관리 
function thumb_object(img_path_filename)  
{
	this.img_path = "";

	this.img_filename = "";
	this.img_path_filename = "";

	this.thumb_filename = "";
	this.thumb_path_filename = "";

	var arr = img_path_filename.split('/'); 

	this.img_filename = arr[arr.length-1];
	this.img_path_filename = img_path_filename;

	this.thumb_filename = "thumb_" + arr[arr.length-1];
	this.img_path = img_path_filename.substring( 0, img_path_filename.length - arr[arr.length-1].length);

	this.thumb_path_filename = this.img_path + this.thumb_filename;
}

//END
