var win = null;

/**
 * IE 이미지 깜빡이는 버그 제거.
 * 참고 : 
 * No more IE6 background flicker - http://evil.che.lu/2006/9/25/no-more-ie6-background-flicker
 * MS의 execCommand설명 - http://msdn2.microsoft.com/en-us/library/ms536419(VS.85).aspx
 * Available memory decreases when you view a Web page in Internet Explorer 6 Service Pack 1 - http://support.microsoft.com/kb/823727
 * High Performance Web Sites > Avoid CSS Expressions - http://stevesouders.com/examples/rule-expr.php
 * @author 최창환
 */
try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}

/**
 *
 */
function getKeyCodes(e) {
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
		
	var character = (String.fromCharCode(code)).toLowerCase();
	var ctrlPressed = e.ctrlKey;
	var shiftPressed = e.shiftKey;
	var altPressed = e.altKey;
	var commandPressed = false;
	if (e.metaKey) {
		commandPressed = e.metaKey;
	}
	
	var returnValue = {
		ctrl : ctrlPressed,
		alt : altPressed,
		shift : shiftPressed,
		command : commandPressed,
		key : character
	}
	
	return returnValue;
}


// 좌우공백제거
// 사용 예 : document.getElementById("id").value = document.getElementById("id").value.trim();
String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g, "");
}


////
// 객체의 value가 src라면 replace 를 대체한다.
//
// @param	string objectID : value를 대체 할 오브젝트의 id
// @param	string src : 검색할 text
// @param	string replace : 대체될 text
// @sample	onclick="javascript:replace_value('search', '아이디', '');"
// @sample	onblur="javascript:replace_value('search', '', '아이디');"
// @return	bool
//
function replace_value(objectID, src, replace)
{
	if( document.getElementById(objectID) == null )
		return false;
	if ( document.getElementById(objectID).value == src )
		document.getElementById(objectID).value = replace;
	return true;
}

// 플래시 스크립트
function printFlashObject(flash_src,name,width,height,option_param_tag){
	obj_html = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0' width='"+width+"' height='"+height+"' id='"+name+"' align='middle'>\
	<param name='allowScriptAccess' value='always' />\
	<param name='movie' value='"+flash_src+"' />\
	<param name='quality' value='high' />\
	<param name='bgcolor' value='#ffffff' />\
	<param name='wmode' value='transparent'>\
	<param name='menu' value='false'>";
	obj_html = obj_html + option_param_tag;
	obj_html = obj_html + "<embed src='"+flash_src+"' quality='high' bgcolor='#ffffff' width='"+width+"' height='"+height+"' name='"+name+"' align='middle' allowscriptaccess='sameDomain' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />\
	</object>";
	document.write(obj_html);
}

function moveCenter() {
	var left = (screen.width-this.width)/2-10;
	var top = (screen.height-this.height)/2-27;
	this.moveTo(left,top);
}

//팝업 가운데 띄우기
function popCenter(mypage,myname,w,h,scroll){
	var winl = (screen.width-w)/2-10;
	var wint = (screen.height-h)/2-27;
	var settings  ='height='+h+',';
			settings +='width='+w+',';
			settings +='top='+wint+',';
			settings +='left='+winl+',';
			settings +='scrollbars='+scroll+',';
			settings +='resizable=no';
	win=window.open(mypage,myname,settings);
	if(parseInt(navigator.appVersion) >= 4){win.focus();}
}

// 팝업 띄우기(name이 같을경우 focus처리)
function popFocus(mypage,myname,settings) {
	win=window.open(mypage,myname,settings);
	if(parseInt(navigator.appVersion) >= 4){win.focus();}
}



function body_click() {

}

/**
 * 빈칸에 텍스트 넣고 빼기 (군영표시에 사용)
 */
var fill = new Array();
fill['txtTeam1'] = '찬성군';
fill['txtTeam2'] = '반대군';

/**
 * 텍스트박스를 빈칸으로 만들기
 */
function showEmptyBox(obj, str){
	var object = $(obj);
	
	if(object.value == str){
		object.value = "";
	}
	
	//fill[obj.id] = str;
}

/**
 * 텍스트박스에 내용 체우기
 */
function showFilledBox(obj) {
	var object = $(obj);
	
	if (object.value == "")
		object.value = fill[obj.id];
}

//사용자 보기
function showUserInfo(userno){
	//위, 왼쪽 스크롤 레퍼런스화 
	var intScrollTop = document.body.scrollTop; 
	var intScrollLaft = document.body.scrollLeft; 
	 
	//이벤트 발생위치 좌표(마우스 클릭위치) 레퍼런스 
	var intClientY = window.event.clientY; 
	var intClientX = window.event.clientX; 
	 
	//나타낼 디스플레이 좌표 레퍼런스 
	var intThisPositionTop = intClientY + intScrollTop; 
	var intThisPositionLeft = intClientX + intScrollLaft; 

	//레퍼런스를 실제 적용 
	zoneUserInfo.style.left = intThisPositionLeft; 
	zoneUserInfo.style.top  = intThisPositionTop; 

	zoneUserInfo.style.display = 'block'; 

	document.getElementById("UserInfo_UserNo").value=userno;


	var params = "id="+userno;
	new Ajax.Updater("zoneUserInfoFriend", "../puser/p_userinfo_getf.php", {
		asynchronous:true,
		parameters:params,
		evalScripts:true
	});

}
//전우추가
function addUserF(id){

	var params = "userno="+id;
	new Ajax.Updater("divImsi", "../puser/p_add_userf.php", {
		asynchronous:true,
		parameters:params,
		evalScripts:true,
		onComplete:addUserF_C(id)
	});

	//정보창끄기		
	zoneUserInfo.style.display = 'none'; 
}
//전우끊기
function disUserF(id){
	var params = "userno="+id;
	new Ajax.Updater("divImsi", "../puser/p_dis_userf.php", {
		asynchronous:true,
		parameters:params,
		evalScripts:true,
		onComplete:addUserF_C(id)
	});

	//정보창끄기		
	zoneUserInfo.style.display = 'none'; 
}
//난중일기보기
function goUserDiary(id){
	var url="../pdiary/me.php?mnu1_type=2&searchType="+id;
	zoneUserInfo.style.display = 'none'; 
	document.location = url;
	//window.open(url, '_blank', 'width=740, height=600 scrollbars=yes, status=no, menubar=no');
}

function addUserF_C(id){
	//Element.toggle("zoneDiaryItem"+id);
	//document.location.reload();
}

//쪽지보내기
function sendPaper(id, type){
	var w,h;
	switch(type){
		case 0:
			w=400;
			h=250;
			break;
		case 1:
			w=400;
			h=355;
			break;
	}
	popCenter("../paper/paper_send.php?type="+type+"&ruser="+id,"paper_send",w,h,"no");
}

//쪽지보기
function viewPaper(id, type){
	var w,h;
	switch(type){
		case 0:
			w=430;
			h=250;
			break;
		case 1:
			w=430;
			h=350;
			break;
		case 2:
			w=430;
			h=350;
			break;
	}
	popCenter("../paper/paper_view.php?type=1&id="+id,"paper_view",w,h,"yes");
}


// 사용자정보
function viewUserProfile(id){
	//window.open("../user/profile.php?userno="+id, '_blank', 'width=740, height=600 scrollbars=yes, status=yes, menubar=yes, resizable=yes, toolbar=yes, location=yes,');
	document.location="../user/profile.php?userno="+id;
}


// 확인 : 로그인 및 가입 요청 + SSO
function needLogin(ssosite,ssoid)
{
	// SSO 사이트
	if( (ssosite != "") && (ssosite != undefined) )
	{
		// // SSO 사이트에 로그인을 하고 SSO 사이트 티워 서비스 가입에 동의를 하지 않은 회원이 접속하면 SSO 동의여부를 묻는다.
		if( (ssoid != "") && (ssoid != undefined) )
		{
			var retConfirm = confirm("동의를 하셔야 티워를 이용하실 수 있습니다.\n동의시 티워 가입에 필요한 최소한의 개인정보를 제공합니다.(약관 참조)");
		
			if(retConfirm)
			{
				query_ssoRuleView();
			}
		}
		
		// SSO 사이트에 로그인을 하지 않았다면
		else
		{
			var retConfirm = confirm("로그인이 필요합니다. 로그인하시겠습니까?");
		
			if(retConfirm)
			{
				document.location = ssosite;		// SSO 사이트 로그인 화면으로 이동
			}
		}
	}

	else if(confirm("회원가입이 필요합니다. 단 30초 밖에 걸리지 않는 간단한 회원가입! 지금 하시겠습니까?"))
	{
		document.location="../user/join_form.php";
	}
}


// 확인 : 인증관련(실명 인증, 본인 확인, 성인 인증)
function needCert(certUrl)
{
	// 인증 url
	if( (certUrl != "") && (certUrl != undefined) )
	{
		var retConfirm = confirm("인증이 필요합니다.");
		
		if(retConfirm)
		{
			document.location = certUrl;		// 인증 url
		}
	}
}

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


function getCookie(name){
    var nameOfCookie = name + "=";
    var x = 0;
    while ( x <= document.cookie.length ){
        var y = (x+nameOfCookie.length);
        if ( document.cookie.substring( x, y ) == nameOfCookie ) {
            if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 ) {
                endOfCookie = document.cookie.length;
            }
            return unescape( document.cookie.substring( y, endOfCookie ) );
        }
        x = document.cookie.indexOf( " ", x ) + 1;
        if ( x == 0 )
        break;
    }
    return "";
}


/**
 * 레이어 위에 이미지를 덮어 보여주기
 */
function showImgIntoLayer(id, path, x, y){

	var img = new Element('img');

	img.setStyle({
		'left' : x + 'px',
		'top' : y + 'px',
		'position' : 'absolute',
		'display' : 'block'
	});	

	img.src = path;

	//document.getElementsByTagName('body')[0].insert(img);
}


// 확인 : 한글
function isKorean(str)
{
	for(var i=0, c; i<str.length; i++){
		c=str.charCodeAt(i);
		if(c < 0xAC00 || 0xD7A3 < c)
			return false;
	}
	return true;
}


// 확인 : 영문
function isEnglish(str)
{
	for(var i=0, c; i<str.length; i++)
	{
		c=str.charCodeAt(i);
		if((c < 65 || 90 < c) && (c < 97 || 122 < c))
			return false;
	}
	
	return true;
}


// 확인 : 숫자
function isNumber(num)
{
	for(var i=0, c; i<num.length; i++)
	{
		c=num.charCodeAt(i);
		if(c < 48 || 57 < c)
			return false;
	}

	return true;
}


// 확인 : 영문/숫자
function isEngNum(str)
{
	for(var i=0; i<str.length; i++)
	{
		c=str.charCodeAt(i);

		if( (c < 48 || 57 < c) && (c < 65 || 90 < c) && (c < 97 || 122 < c) )
			return false;
	}
	
	return true;
}


// 확인 : 탭, 띄어쓰기
function isTabSpace(str)
{
	for(var i=0; i<str.length; i++)
	{
		c=str.charCodeAt(i);
		
		// 콤마, 탭문자
		if(c == '9' || c == '32')
		{
			return false;
		}
	}
	
	return true;
}


// 확인 : (탭,띄어쓰기,콤마,마침표,",',`,+,-,*,/,?,#,$,%,&,:,;,<,>)
function isSpecialChar(str)
{
	for(var i=0; i<str.length; i++)
	{
		c=str.charCodeAt(i);

		if(c == '9' || c == '32' || c == '44' || c == '46' || c == '34' || c == '39' || c == '96' 
				|| c == '43' || c == '45' || c == '42' || c == '47' || c == '63' || c == '35' || c == '36' 
				|| c == '37' || c == '38' || c == '58' || c == '59' || c == '60' || c == '62')
		{
			return false;
		}
	}
	
	return true;
}


// 확인 : 아이디
function isID(str)
{
	var c = str.charCodeAt(0);

	for(var i=0; i<str.length; i++)
	{
		c=str.charCodeAt(i);

		// 콤마, 탭문자
		//if( (c < 48 || c > 57) && (c < 65 || 90 < c) && (c < 97 || 122 < c) )
		
		// 숫자, 영문(대,소)
		if( (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) )
		{
		}
		
		else
		{
			// 메일 형식, @, . 은 제외
			if(c == 64 || c == 46)
			{		
				return true;
			}
			
			return false;
		}
	}

	return true;
}


// 확인 : 전화번호
function isCellPhone(num)
{
	if(num[0].length<3 || num[1].length<3 || num[2].length<4)
		return false;
	for(var i=0; i<num.length; i++)
		if(!isNumber(num[i]))
			return false;
	return true;
}

/**
 * 이미지 로딩에 실패 시 다른 이미지로 교체
 *
 * @param HTMLImageElement img
 * @param string option
 */
function imgerror(img, option) {
	switch (option) {
	case "remove":
		img.parentNode.removeChild(img);
		return;
	}
	
	var src	= "http://image1.twar.co.kr/images/userthumb/no_img.jpg";
	var width	= img.getAttribute("width");
	var height	= img.getAttribute("height");
	
	if (width && height) {
		if (isIE6())
			src = "http://image1.twar.co.kr/image.php?url=images/userthumb/no_img.jpg&width=" + width + "&height=" + height;
		else
			src += "?width=" + width + "&height=" + height;
	}

	img.setAttribute("src", src);
	
	img.onerror = function(){
		imgerror(this, "remove");
	};
}

/**
 * 현재 브라우저가 IE6인지 확인
 *
 * @return bool
 */
function isIE6() {
	if (isIE6.value == undefined)
		isIE6.value = navigator.userAgent.search(/MSIE 6\.0/) != -1;
	return isIE6.value;
}

/**
 * 팝언더 창을 연다.
 */
function open_popunder(url, parenturl, iframeurl, timeout) {
	win2 = window.open('about:blank', 'ad' ,'location=1, directoryies=1, resizable=1, status=1, toolbar=1, scrollbars=1, memubar=1, width=0, height=0, left=9999, top=9999');
	win2.blur();
	window.focus();
	
	//win2.document.write('<script type="text/javascript">setTimeout(function() {window.close();}, '+closetimeout+');</script>');
	win2.document.write('<iframe src="'+iframeurl+'" height="0" width="0" frameborder="0"></iframe><script type="text/javascript">var parenturl = "'+parenturl+'"; setTimeout(function() { if (opener.location.href.indexOf(parenturl) < 0) { window.close(); return false; } location.href="'+url+'"; window.focus(); var screenSizeWidth,screenSizeHeight; if (self.screen) { screenSizeWidth = screen.width; screenSizeHeight = screen.height; } intWidth = screenSizeWidth; intHeight = screenSizeHeight; intXOffset = 0; intYOffset = 0; window.moveTo( 0, 0 ); window.resizeBy(intWidth, intHeight); }, '+timeout+');</script>');

/*
	setTimeout(function() {
		window.blur();
		win2.focus();
		
		var screenSizeWidth,screenSizeHeight;
		if (self.screen) {
			screenSizeWidth = screen.width;
			screenSizeHeight = screen.height;
		}
		
		intWidth = screenSizeWidth;
		intHeight = screenSizeHeight;
		intXOffset = 0;
		intYOffset = 0;
		
		win2.moveTo( 0, 0 ); 
		win2.resizeBy(intWidth, intHeight);
		win2.location.href = url;
	}, timeout);
*/
}