var isIE = (navigator.appName.indexOf("Microsoft") != -1) ? 1 : 0;
var isIE70 = (navigator.appVersion.indexOf("MSIE 7.0") != -1) ? true : false;

function SetCookie(name, value, expires, path, domain, secure) { //expires => 초
	var date = new Date();
	date.setSeconds(date.getSeconds() + expires);

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

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 DelCookie(name, path, domain)
{
    if (GetCookie(name)) {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function OpenDialog(nLink, nWin, nWidth, nHeight, xPos, yPos) {
	if(typeof nLink == "object") url = nLink.href;
	else url = nLink;
	var qResult = window.showModalDialog( url, nWin, "dialogwidth:"+nWidth+"px;dialogheight:"+nHeight+"px;toolbar:no;location:no;help:no;directories:no;status:no;menubar:no;scroll:no;resizable:no");
}

function OpenWindow(nLink, nTarget, nWidth, nHeight, xPos, yPos) {
	if(typeof nLink == "object") url = nLink.href;
	else url = nLink;

	adjX = xPos ? xPos : (window.screen.width/2 - nWidth/2);
	adjY = yPos ? yPos : (window.screen.height/2 - nHeight/2 - 50);
	var qResult = window.open( url, nTarget, "width="+nWidth+", height="+nHeight+",left="+adjX+",top="+adjY+",toolbar=no,status=yes,scrollbars=no,resizable=no");
	return qResult;
}

function OpenWindows(nLink, nTarget, nWidth, nHeight, xPos, yPos) {
	if(typeof nLink == "object") url = nLink.href;
	else url = nLink;

	adjX = xPos ? xPos : (window.screen.width/2 - nWidth/2);
	adjY = yPos ? yPos : (window.screen.height/2 - nHeight/2 - 50);
	var qResult = window.open( url, nTarget, "width="+nWidth+", height="+nHeight+",left="+adjX+",top="+adjY+",toolbar=no,status=yes,scrollbars=1,resizable=no");
	return qResult;
}

function ConfirmAction(obj) {
	if(confirm(obj.name + " 하시겠습니까?")) {
		location.href = obj.href;
	}
}

function BtnConfirmGo(obj, url) {
	var msg;
	if(typeof obj == "object") msg = obj.value;
	else msg = obj;
	if(confirm(msg + " 하시겠습니까?")) {
		location.href = url;
	}
}

function Go(url) {
	location.href = url;
}

function IfGo(msg, url, url2) {
	if(confirm(msg)) Go(url);
	else {
		if(!url2) return false;
		else Go(url2);
	}
	return true;
}

function ResizeImage(el, w, h) {
	try
	{

		if(el.width > 0) w = el.width;
		if(el.height > 0) h = el.height;

		var img = new Image();
		img.onload = function() {
			if(w > img.width) el.width = img.width;
			if(h > img.height) el.height = img.height;

			var sheight = el.width * img.height / img.width;
			var swidth = el.height * img.width / img.height;

			if(swidth < el.width) el.width = swidth;
			if(sheight < el.height) el.height = sheight;
			//alert(el.width);
		}
		img.src = el.src;
	}
	catch (e) {}
}

function ImageError(el, url) {
	var noimg = new Image();
	noimg.src = url ? url : "../html/images/blank.gif";
	noimg.onerror = function() { 
		alert("[개발 Debug] common.js - function ImageError() 오류 : \n" + noimg.src + ' 파일이 존재 하지 않습니다.'); 
	}
	if(el) el.src = noimg.src;
}

function ShowLayer(n) {
	var el = document.getElementById(n);
	if(el) {
		el.style.display = 'block';
	}
}

function HideLayer(n) {
	var el = document.getElementById(n);
	if(el) {
		el.style.display = 'none';
	}
}

function AutoLayer(n) {
	var el = document.getElementById(n);
	if(!el) return;
	if(el.style.display == 'none') {
		el.style.display = 'block'
	} else {
		el.style.display = 'none'
	}
}

function validate(el) {
	return true;
}

function SetFormValue(f, n, v, sep) {
	var f = document.forms[f];
	if(!f || !f[n]) return false;
	switch(f[n].type) {
		case 'text':
		case 'password':
			f[n].value = v;
			break;
		case 'textarea':
			f[n].text = v;
			break;
		case 'checkbox':
				if(f[n].value == v) f[n].checked = true;
			break;
		case 'select-one':
			for(var i=0; i<f[n].options.length; i++) if(f[n].options[i].value == v) f[n].options[i].selected = true;
			break;
		default:
			if(sep) {
				var val = v.split(sep);
				for(var i=0; i<f[n].length; i++) {
					for(var j=0; j<val.length; j++) {
						if(f[n][i].value == val[j])  f[n][i].checked = true;
					}
				}
			}
			else {
				for(var i=0; i<f[n].length; i++) if(f[n][i].value == v) f[n][i].checked = true;			
			}
			break;
	}
}

function GetFormValue(f, n) {
	var f = document.forms[f];
	if(!f || !f[n]) return false;
	switch(f[n].type) {
		case 'text':
		case 'file':
		case 'password':
			return f[n].value;
			break;
		case 'textarea':
			return f[n].text;
			break;
		case 'checkbox':
			return f[n].checked ? f[n].value : "";
			break;
		case 'select-one':
			for(var i=0; i<f[n].options.length; i++) {
				if(f[n].options[i].selected == true) {
					return f[n].options[i].value;
				}
			}
			break;
		default:
			var arr = new Array();
			var j = 0;
			for(var i=0; i<f[n].length; i++) {
				if(f[n][i].checked == true) {
					 arr[j] = f[n][i].value;
					 j++;
				}
			}
			return arr.join(",");
			break;
	}
}

var AUTO_CHECK_STATUS = true;

function AutoCheck(f, n) {
	var f = document.forms[f];
	if(!f || !f[n]) return;
	if(typeof(f[n]) == "object") {
		if(f[n].length) {
			for(var i=0; i<f[n].length; i++) {
				f[n][i].checked = AUTO_CHECK_STATUS;
			}
		} else {
			f[n].checked = AUTO_CHECK_STATUS;
		}
		if(AUTO_CHECK_STATUS == true) {
			AUTO_CHECK_STATUS = false;
		} else {
			AUTO_CHECK_STATUS = true;
		}
	}
}

function CheckGo(f, n, url, msg, conf_msg) {
	var idx = GetFormValue(f, n);

	if(idx == "") {
		alert(msg);
	} else {
		if(conf_msg && !confirm(conf_msg)) return;

		if(url.indexOf("javascript:") != -1) {
			eval(url.replace("javascript:", ""));
		} else {
			location.href=url + idx;
		}
	}
}

function ResizeIframe(n) {
	var h;
	if(el = parent.document.getElementById(n)) {
		if(isIE) h = document.body.scrollHeight;
		else h = document.body.offsetHeight;
		if(h > 10) el.height = h;
		else el.height = 0;
	}
}

function GoNext(fm,pos,size) {

	if(fm.elements[0].name == "PHPSESSID") {
		pos++;
	}

	next_pos = pos + 1;
	value = fm.elements[pos].value;
	len = value.length;
	is_num = IsNumeric(value);

	if(!is_num) {
		if((len > 0) && (value != '0') && (value != '00') && (value != '000')) {
			alert('숫자를 넣어주세요');
			fm.elements[pos].select();
			fm.elements[pos].focus();
			return false;
		}
	}
	
	if(len == size) {
		fm.elements[next_pos].focus();
		return true;
	}
}

function MoveNext(el, next, size) {
	var len = el.value.length;
	if(len == size) {
		next.focus();
		return true;
	}
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789.-";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
         IsNumber = false;
      }
   }

   return IsNumber;
}

function OnlyNumber(el) {
	if(!IsNumeric(el.value)) {
		el.value = "";
		el.focus();
	}
}

function PhotoViewer(el) {
	var photo = new PhotoLayer();
	photo.Initialized();
	photo.doPhotoClick(el);
}

function DrawBar(cnt, max, color) {
	var percent;
	if(max > 0) {
		percent = Math.floor((cnt / max) * 100);
	} else {
		percent = 0;
	}
	var other = 100 - percent;
	document.write("<table width='400' cellpadding=0 cellspacing=0 height=10><tr><td width='"+percent+"%' background='../html/images/stat/s_bg_"+color+".gif'></td><td width='"+ other +"%'></td></tr></table>");
}

function initTinyMCE(theme, mode, els) {
	if(!theme) theme = "advanced";
	if(!mode) mode = "textareas";
	if(!els) els = "content";


	tinyMCE.init({
		mode : mode,
		theme : theme,
		elements : els,
		plugins : "table,emotions,media,layer,preview",
		//theme_advanced_fonts : "굴림=굴림,arial;돋움=돋움,arial;바탕=바탕,arial;궁서=궁서,arial;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sand;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Verdana=verdana,geneva",
		theme_advanced_buttons1 : "fontselect,fontsizeselect,separator,bold,italic,underline,strikethrough,separator,forecolor,backcolor,separator,justifyleft,justifycenter,justifyright",
		theme_advanced_buttons2 : "undo,redo,separator,bullist,numlist,outdent,indent,separator,link,unlink,anchor,image,emotions,media,table,insertlayer,separator,hr,removeformat,separator,preview,code",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		//content_css : "../../html/css/style.css",
		//file_browser_callback : "fileBrowserCallBack",
		theme_advanced_resizing : true,
		theme_advanced_resize_horizontal : false,
		relative_urls : false,
		remove_script_host : true,
		convert_urls : true,
		//extended_valid_elements : "object[classid|codebase|width|height|align],param[name|value],embed[quality|type|pluginspage|width|height|src|align]",
		extended_valid_elements : "object[classid|codebase|width|height|align],param[name|value],embed[quality|type|pluginspage|width|height|src|align],area[shap|coords|href|target],map[class|name]",
		verify_html : true,
		apply_source_formatting : true,
		button_tile_map : true,
		entity_encoding : "raw",
		language : "en"
	});
}

function fileBrowserCallBack(field_name, url, type, win) {
	// This is where you insert your custom filebrowser logic
	OpenWindows("/board/fileman.php", '', 700, 600);

	// Insert new URL, this would normaly be done in a popup
	win.document.forms[0].elements[field_name].value = "someurl.htm";
}

function InsertContent(url) {
	var arr = url.split(".");
	var ext = arr[arr.length - 1];
	var content = "";
	var click_photo = ""

	click_photo = "photo.doPhotoClick(this)";

	switch (ext.toLowerCase()) {
		case "gif":
		case "jpg":
		case "png":
		case "bmp":
			content = '<img src='+ url +' onclick="'+click_photo+'" style="cursor:pointer;width:400px;">';
			break;
		case "swf":
			var width = 200;
			var height = 200;
			content += ''
			+ '<img src="' + (tinyMCE.getParam("theme_href") + "/images/spacer.gif") + '" mce_src="' + (tinyMCE.getParam("theme_href") + "/images/spacer.gif") + '" '
			+ 'width="' + width + '" height="' + height + '" '
			+ 'border="0" alt="' + url + '" title="' + url + '" class="mceItemFlash" />';
			break;
		case "mov":
			content = getEmbedTag(url, '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime');
			break;
		case "ra":
			content = getEmbedTag(url, 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin');
			break;
		case "wmv":
		case "wma":
		case "asf":
		case "mp3":
		case "avi":
			content = getEmbedTag(url, '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2');
			break;
		default:
			return;
	}
	tinyMCE.execCommand('mceFocus',false,'content'); 
	tinyMCE.execCommand('mceInsertContent',false, content);
}

function getEmbedTag(url, cls, cb, mt, d) {
	var h = '', n;
	h = '<embed type="' + mt + '" src="'+ url +'" alt="multiupload" wmode="transparent"></embed>';
	return h;
}

function call(url, id) {

	if(!id) id = "AJAX_DIV";
	var client = false;

	if(window.ActiveXObject) {
		try {
			client = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				client = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {}
		}
	} else {
		client = new XMLHttpRequest();
	}
	if(client) {
		client.onreadystatechange = function() {
			if(client.readyState == 4) {

				//출력레이어가 없을 경우 생성
				var el = document.getElementById(id);
				if(!el) {
					el = document.createElement("div");
					el.style.display = 'none';
					document.body.appendChild(el);
				}
				
				//IE의 경우 버그가 존재함. 그래서 &nbsp;를 추가
				if(isIE && client.responseText.indexOf("<script") == 0) {
					el.innerHTML = "&nbsp;" + client.responseText;
				} else {
					el.innerHTML = client.responseText;
				}

				//자바스크립트 실행 (defer는 IE 에서 실행되어 안씀)
				var scripts = el.getElementsByTagName("script");
				for(var i=0; i<scripts.length; i++) {
					eval(scripts[i].innerHTML.replace("<!--", "").replace("-->", ""));
				}
			}
		}
		var f;
		if(f = document.forms[url]) {
			var parameters = "";
			for(var i=0; i<f.elements.length; i++) {
				if(f.elements[i].name == "") continue; 
				if(f.elements[i].type == "radio" || f.elements[i].type == "checkbox") {
					if(f.elements[i].checked == false) continue;
				}
				//parameters += f.elements[i].name + "=" + encodeURI( f.elements[i].value ) + "&";
				parameters += f.elements[i].name + "=" + escape( f.elements[i].value ) + "&";
			}
			if(!f.action) f.action = location.href;
			client.open('POST', f.action, true);
			client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			client.setRequestHeader("Content-length", parameters.length);
			client.setRequestHeader("Connection", "close");
			client.send(parameters);
		} else {
			client.open("GET", url, true);
			client.send(null);
		}
	}
}

function docWrite(str) {
	document.write(str);
}

function playFlash(filename, width, height, id, trans, params, lock) {
	id = id ? id : "";
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+width+'" height="'+height+'" id="'+id+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="movie" value="'+filename+'" /><param name="menu" value="false" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><param name="wmode" value="'+trans+'" />' + (params ? '<param name="FlashVars" value="' + params + '" />' : "") + '<embed src="'+filename + (params ? '?' + params : "") +'" menu="false" quality="high" bgcolor="#ffffff" wmode="' + trans + '" width="'+width+'" height="'+height+'" name="'+id+'" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>');

}

function FlashChart(id, width, height, xmlurl, ftype) {
	var filename = "FlashChart.swf";
	if(ftype == "mini") filename = "FlashChartMini.swf";
	playFlash("/lib/js/" + filename, width, height, id, "transparent", "xmlurl=" + escape(xmlurl));
}

function ToggleLayer(tarName, objName, addX, addY, flag) {
	var obj = (typeof(objName) == 'object') ? objName : document.getElementById(objName);	
	var tar = document.getElementById(tarName);
	if(obj && tar) {

		var curleft = curtop = 0;
		if (obj.offsetParent) {
			do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);
		}

		tar.style.position = "absolute";
		tar.style.left = curleft + (addX ? parseInt(addX) : 0);
		tar.style.top = curtop + (addY? parseInt(addY) : 0);

		if(!flag) {
			if(tar.style.display == "none") {
				tar.style.display = "block";
			} else {
				tar.style.display = "none";
			}
		} else {
			tar.style.display = "block";
		}
	}	
}


//숫자를 통화 포멧으로 반환  
function numFormat(value) { 
	return String(value).replace(/(\d)(?=(?:\d{3})+(?!\d))/g,"$1,"); 
} 

function setSubCategory(url, obj, keys, f) {
    if(!f) f = 'form1';
    var captions = new Array();
    var values = new Array();
    var attributes = new Array();
    var attributeNames = new Array("hname", "required");
    var area = "";
    var u = escape(url);
 
    for(var i=0; i<keys.length; i++) {
        var el = document.forms[f][keys[i]];
        captions[i] = el.length > 0 && el[0].text ? el[0].text : "";
        values[i] = el.value;
        attributes[i] = "";
        for(var j=0; j<attributeNames.length; j++) {
        	if(el.getAttribute(attributeNames[j])) {
            	attributes[i] += attributeNames[j] + ":'" + el.getAttribute(attributeNames[j]) + "', " ;
			}
		}
        attributes[i] = "{" + attributes[i].substring(0, attributes[i].length - 2) + "}";
 
        if(obj.name == keys[i] && keys[i+1] != null) area = keys[i+1];
        if(obj.name == keys[i]) var idx = i;
    }
    url += url.indexOf("?") != -1 ? "&" : "?";
    url += "idx=" + idx;
    url += "&captions=" + captions.join(",");
    url += "&keys=" + keys.join(",");
    url += "&values=" + values.join(",");
    url += "&attributes=" + attributes.join("__");
    url += "&form=" + f;
    url += "&url=" + u;
    call(url, area);
}

Offset = function(element) {
	this.obj = element;
	this.left;
	this.top;
	this.height;
	this.width;
	this.getOffset();
}
Offset.prototype.getOffset = function() {
	var obj = this.obj;
	var top = left = 0;
	if (obj.offsetParent) {
		do {
			top += obj.offsetTop;
			left += obj.offsetLeft;
		} while (obj = obj.offsetParent);
	}
	this.left = left;
	this.top = top;
	this.width = this.obj.offsetWidth;
	this.height = this.obj.offsetHeight;
}
