﻿function Global_SetCookie( name, value, expiredays )
{
	var todayDate = new Date();
	todayDate.setDate( todayDate.getDate() + expiredays );
	document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}

// 쿠키에 입력된 값을 가지고 옵니다. --------------------------------------------------------------------------------
function Global_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 Global_ResizeWIndow(width, height)
{
    window.resizeTo(width,height);
}

function Global_ResizeImage(areaID, maxWidth)
{  
	var contentObject = document.getElementById(areaID);
	
	Global_FindImgObject(contentObject, maxWidth);
}

function Global_FindImgObject(parentsObject, maxWidth)
{
	for(var i=0;i<parentsObject.children.length;i++)
	{
		if(parentsObject.children[i].tagName == "IMG")
		{
			var img = parentsObject.children[i];

			var width = img.width;
			var height = img.height;

			if (width > maxWidth)
			{
			    img.sourceWidth = img.width;
			    img.sourceHeight = img.height;
			    
				img.width = maxWidth;
				img.height = (maxWidth*height) / width;
				img.title = "클릭하시면 원본 이미지를 보실 수 있습니다.";
				img.style.cursor = "hand";
				img.attachEvent('onclick', OnResizedImageClick);
			}
		}
		else if(parentsObject.children[i].children.length > 0)
		{  
			Global_FindImgObject(parentsObject.children[i], maxWidth);
		}
	}
}

function OnResizedImageClick()
{  
    var sourceObject = event.srcElement;
    
    var width = sourceObject.sourceWidth;
    var height = sourceObject.sourceHeight; 

    var screenX = (event.clientX) - (width/2);    
    var screenY = (event.clientY) + (height/2) - 100;
    
    var resizedImagePopUp = window.open('','resizedImage','top='+screenY+',left='+screenX+',width='+width+',height='+height);
    
    resizedImagePopUp.document.write("<html>");
    resizedImagePopUp.document.write("<title>이미지 원본</title>");
    resizedImagePopUp.document.write("<body style='margin:0px'>");
    resizedImagePopUp.document.write("<img src='"+sourceObject.src+"' onclick='self.close();' title='클릭하면 창을 닫습니다.' style='cursor:hand'>");
    resizedImagePopUp.document.write("</body>");
    resizedImagePopUp.document.write("</html>");
}

// 해당 텍스트 값에서 확장자를 추출합니다.

function Global_GetFileExtension( controlObject )
{
	var contolValue = controlObject.value;

	var index = contolValue.lastIndexOf(".")

	if ( ( Global_TrimSpaces(contolValue) != "" ) && ( contolValue.length != 0 ) )
	{
		return contolValue.substring(index+1).toLowerCase();
	}
	else
	{
		return '';
	}
}

// Javascript로 QueryString 구하기 ---------------------------------------------------------------------------------------------
function Global_Request(valuename)
{
    var rtnval = "";
    var nowAddress = unescape(location.href);
    var parameters = (nowAddress.slice(nowAddress.indexOf("?")+1,nowAddress.length)).split("&");

    for(var i = 0 ; i < parameters.length ; i++){
        var varName = parameters[i].split("=")[0];
        if(varName.toUpperCase() == valuename.toUpperCase())
        {
            rtnval = parameters[i].split("=")[1];
            break;
        }
    }

    return rtnval;
}

// 두개의 컨트롤의 값을 비교해서 같은지를 반환합니다. --------------------------------------------------------------------------
function Globl_ControlToControlValueCheck(sourceControlName, targetControlName, message)
{
    var sourceControl = FindObject(sourceControlName);
    var targetControl = FindObject(targetControlName);

    if(sourceControl == null || targetControl == null)
    {
        alert("한개의 이상의 컨트롤이 없습니다.");
        return false;
    }
    else
    {
        if ( Global_TrimSpaces(sourceControl.value) != Global_TrimSpaces(targetControl.value) )
        {
            alert(message);
            return false;
        }
        else
        {
            return true;
        }

    }
}

// 이메일의 형식을 체크합니다. -------------------------------------------------------------------------------------
function Global_EmailCheck( emailValue )
{
	if(emailValue != "")
	{
		if(Global_TrimSpaces(emailValue) != "")
		{
			var chkEmail = emailValue.match(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/);

			if (chkEmail == null)
			{
				alert("메일 주소의 형식이 올바르지 않습니다.");				
				return false;
			}
			else
			{
			    return true;
			}
		}
		else
		{
			return true;
		}
	}
	else
	{
		return true;
	}
}

// 해당 창 크기의 정 중앙 좌표를 가지고 옵니다.
function Global_Width(popupWindowWidth)
{
    return (document.body.clientWidth/2) - (popupWindowWidth/2);
}

function Global_Height(popupWindowHeight)
{
    return (document.body.clientHeight/2) - (popupWindowHeight/2);
}

// 창을 중앙/이벤트 발생 위치하도록 엽니다.
function WindowCenterOpen(url, name, width, height, enableScroll, isCenter)
{
    var properties = "width="+width;
    properties += ", height="+height;
    
    if(isCenter)
    {
        properties += ", left="+Global_Width(width);
        properties += ", top="+Global_Height(height);
    }
    else
    {
        properties += ", left="+(window.event.clientX+10);
        properties += ", top="+(window.event.clientY+height);
    }
    
    if(enableScroll)
        properties += ", scrollbars=1";
    
    
    var popWindow = window.open(url,name,properties);
    
    if(popWindow == null)
    {
        alert("팝업이 차단되었습니다.");
        return false;
    }
}

// 컨트롤의 Client를 저장합니다.
var clientIDList =  new Array();

// 해당 텍스트 컨트롤이 공백인지를 검사  ---------------------------------------------------------------------------------------
function Global_ControlValueCheck( controlName , message, enableBadWordCheck )
{
    var control = FindObject(controlName);

	if(control != null)
	{
		if ( Global_TrimSpaces(control.value) == '' )
		{
			alert( message );
			control.value = '';
			control.focus();
			return false;
		}
		else
		{
			if(enableBadWordCheck)
			{
				// 불량단어 필터링이 걸릴경우 불량단어를 검사
				return ChkeckBadWord( control );
			}
			else
			{
				return true;
			}
		}
	}
	else
	{
		return true;
	}
}

// 금지단어 등록
var BadWords = "개새끼,소새끼,병신,지랄,씨팔,십팔,니기미,찌랄,지랄,쌍년,쌍놈,빙신,좆까,니기미,좆같은게,잡놈,벼엉신,바보새끼,씹새끼,씨발,씨팔,시벌,씨벌,떠그랄,좆밥,추천인,추천id,추천아이디,추천id,추천아이디,추/천/인,등신,싸가지,미친놈,미친넘,찌랄,죽습니다,님아,님들아,씨밸넘";

function ChkeckBadWord( control )
{
	//  이 함수를 사용하기 위해서는 불량 단어 변수 BadWord를 지정해야 합니다.
	var TempObj = control;

	if(BadWords == null)
	{
		return;
	}

	var BadText = BadWords.split(",");

	if(BadText == "")
	{
		return false;
	}

	var swear_words_arr=new Array();

	for(var i=0;i < BadText.length;i++)
	{
		swear_words_arr = swear_words_arr.concat(BadText[i]);
	}

	var swear_alert_arr=new Array;
	var swear_alert_count=0;

	var compare_text=TempObj.value;

	for(var i=0; i<swear_words_arr.length; i++)
	{
		for(var j=0; j<(compare_text.length); j++)
		{
			if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
			{
				swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
				swear_alert_count++;
			}
		}
	}

	var alert_text="";

	for(var k=1; k<=swear_alert_count; k++)
	{
		alert_text+="\n" + "* " + swear_alert_arr[k-1];
	}

	if(swear_alert_count>0)
	{
		alert("금지된 단어를 사용하였습니다.\n_______________________________\n" + alert_text + "\n_______________________________");
		return false;
	}
	else
	{
		return true;
	}
}

// 컨트롤을 찾습니다. ----------------------------------------------------------------------------------------------
function FindObject(objectName)
{
    var tempObjectName = objectName;

    // 검사대상 컨트롤을 찾습니다.
    // 정의된 clientID리스트를 돕니다.
    for(var i=0;i<clientIDList.length;i++)
    {
        // 객체가 있다.
        if(document.getElementById(clientIDList[i]+"_"+objectName) != null)
        {
            // 아직 컨트롤의 이름이 설정되지 않았다면
            if(tempObjectName == objectName)
            {
                // 이름을 설정
                tempObjectName = clientIDList[i]+"_"+objectName;
            }
        }
    }

    if(document.getElementById(tempObjectName) != null)
    {
        return document.getElementById(tempObjectName);
    }
    else
    {
        return null;
    }
}

// 해당 문자열의 공백을 제거 ----------------------------------------------------------------------------------------------------
function Global_TrimSpaces( text )
{
	var temp = "";

	text = '' + text.toUpperCase();

	splitstring = text.split(" ");

	for(i = 0; i < splitstring.length; i++)

	temp += splitstring[i];

	return temp;
}

function Global_CheckPID ( controlName1, controlName2 ) 
{
	var NUM = "0123456789";
	
	var PID1 = FindObject(controlName1).value;
	var PID2 = FindObject(controlName2).value;

	var chk = 0;

	var nYear = PID1.substring(0,2);

	var nMondth = PID1.substring(2,4);

	var nDay = PID1.substring(4,6);

	var nSex = PID2.charAt(0);

	if (!IsValid(PID1, NUM))
	{
		alert("주민번호가 올바르지 않습니다.");	
		FindObject(controlName1).select();
		return false//-1;
	}
	
	if ( PID1.length!=6 ||  nMondth<1 || nMondth>12 || nDay<1 || nDay>31)
	{
		alert("주민번호가 올바르지 않습니다.");	
		FindObject(controlName1).select();
		return false//-1;
	}
	
	if (!IsValid(PID2, NUM))
	{
		alert("주민번호가 올바르지 않습니다.");	
		FindObject(controlName1).select();
		return false//1;
	}
	
	if ( PID2.length!=7 || (nSex!=1 && nSex!=2 && nSex!=3 && nSex!=4 && nSex!=5 && nSex!=6 && nSex!=7 && nSex!=8) )
	{
		alert("주민번호가 올바르지 않습니다.");	
		FindObject(controlName1).select();
		return false//1;
	}
	
	if ( nSex==5 || nSex==6 || nSex==7 || nSex==8 )
	{
		var sum=0;
		var odd=0;
		var PID = PID1 + PID2;
		buf = new Array(13);
		for (i=0; i<13; i++) buf[i] = parseInt(PID.charAt(i));
		odd = buf[7]*10 + buf[8];
		if (odd%2 != 0)
		{
			alert("주민번호가 올바르지 않습니다.");	
			FindObject(controlName1).select();
			return false//-1;
		}
		
		multipliers = [2,3,4,5,6,7,8,9,2,3,4,5];
		for (i=0, sum=0; i<12; i++) sum += (buf[i] *= multipliers[i]);
		sum = 11-(sum%11);
		if (sum >= 10) sum-= 10;
		sum += 2;
		if (sum >= 10) sum -= 10;
		if ( sum != buf[12] )
		{
			alert("주민번호가 올바르지 않습니다.");	
			FindObject(controlName1).select();
			return false//-1;
		}
	}
	else
	{
		var i;
		for (i=0; i<6; i++)
		{
			chk += ( (i+2) * parseInt( PID1.charAt(i) ));
		}

		for (i=6; i<12; i++)
		{
			chk += ( (i%8+2) * parseInt( PID2.charAt(i-6) ));
		}
		
		chk = 11 - (chk%11);
		chk %= 10;
		
		if (chk != parseInt( PID2.charAt(6)))
		{
			alert("주민번호가 올바르지 않습니다.");	
			FindObject(controlName1).select();
			
			return false//-1;
		}
	}

	return true//0;
}

// 주민등록체크의 서브 함수로 사용됩니다.
function IsValid(s,spc)
{
	var i;
	if (s.length<1) return false;
	for(i=0; i<s.length; i++)
	{
		if (spc.indexOf( s.substring(i, i+1)) < 0)
		{
			return false;
		}
	}

	return true;
}

// 필요한 이미지를 미리 로드 합니다. -------------------------------------------------------------------------------------------
function Global_PreloadImage()
{
	var img_list = Global_PreloadImage.arguments;
	if (document.preloadlist == null)
		document.preloadlist = new Array();
	var top = document.preloadlist.length;
	for (var i=0; i < img_list.length; i++)
	{
		document.preloadlist[top+i]     = new Image;
		document.preloadlist[top+i].src = img_list[i+1];
	}
}

// Select 항목을 조정합니다. ----------------------------------------------------------------------------------------

//항목을 추가합니다.
function Global_AddOption( theForm, text, value)
{
	var newOpt = document.createElement("OPTION");
	newOpt.text = text;
	newOpt.value = value;
	theForm.add(newOpt);
}

// 항목을 제거 합니다.
function Global_ReMoveOption( theForm, selectedIndex )
{
    try
    {
	    var selLength = theForm.length;

	    if ( selLength > 0 )
	    {
		    theForm.remove( selectedIndex );
	    }
    }
    catch(error)
    {
        alert(error.description);
        return false;
    }
}


var select_obj;

function Global_LayerAction(name,status) {

	var obj=document.all[name];
	var _tmpx,_tmpy, marginx, marginy;
	_tmpx = event.clientX + parseInt(obj.offsetWidth);
	_tmpy = event.clientY + parseInt(obj.offsetHeight);
	_marginx = document.body.clientWidth - _tmpx;
	_marginy = document.body.clientHeight - _tmpy ;
	if(_marginx < 0)
		_tmpx = event.clientX + document.body.scrollLeft + _marginx ;
	else
		_tmpx = event.clientX + document.body.scrollLeft ;
	if(_marginy < 0)
		_tmpy = event.clientY + document.body.scrollTop + _marginy +20;
	else
		_tmpy = event.clientY + document.body.scrollTop ;
	obj.style.posLeft=_tmpx-13;
	obj.style.posTop=_tmpy-12;
	if(status=='visible') {
		if(select_obj) {
			select_obj.style.visibility='hidden';
			select_obj=null;
		}
		select_obj=obj;
	}else{
		select_obj=null;
	}
	obj.style.visibility=status; 
}

function Global_ResizeHeight(frm) {
    
    var pFrame = eval(frm + ".document.body;");
	var iFrame = eval("document.all." + frm + ";");

	iFrame.style.height = pFrame.scrollHeight + (pFrame.offsetHeight - pFrame.clientHeight);

}

// 창을 중앙/이벤트 발생 위치하도록 엽니다.
function Global_WindowCenterOpen(url, name, width, height, enableScroll, isCenter)
{   
    var properties = "width="+width;
    properties += ", height="+height;
    
    if(isCenter)
    {
        properties += ", left="+Global_Width(width);
        properties += ", top="+Global_Height(height);
    }
    else
    {
        properties += ", left="+(window.event.clientX+10);
        properties += ", top="+(window.event.clientY+height);
    }
    
    if(enableScroll)
        properties += ", scrollbars=1";
    
    
    var popWindow = window.open(url,name,properties);    
    
    if(popWindow == null)
    {
        alert("팝업 차단기능으로 대화상자를 열 수 없습니다.");        
    }
}

function Global_LoadAttachDialog( controlName, savePath,  fileType )
{
	window.open('/Library/Modules/FileSave.aspx?controlName='+controlName+'&savePath='+savePath+'&fileType='+fileType,'files','width=300,height=200',false);
}

function Global_CreateOption( controlName, text, value, isOppenr )
{
    var fileList;
	var newOption;
	
	if(isOppenr)
	{
	   // 부모의 Select Box
		fileList = opener.document.all[controlName];
		// Option을 만듭니다.
		newOption = opener.document.createElement('OPTION');
	}
	else
	{
	    // 부모의 Select Box
		fileList = document.all[controlName];
		// Option을 만듭니다.
		newOption = document.createElement('OPTION');
	}

	// 옵션에 파일명을 만듬
	newOption.text = text;

	// 옵션에 사이즈를 만듬
	newOption.value = value;

	// 옵션을 추가합니다.
	fileList.add(newOption);

	if(isOppenr)
	{
		self.close();
	}
}

function Global_DeleteAttachDialog( controlName, savePath )
{
	var selectControl = document.all[controlName];
		
	var SelectedfileName = selectControl.options[selectControl.selectedIndex].text;
	
	window.open('/Library/Modules/FileDelete.aspx?controlName='+controlName+'&fileName='+SelectedfileName+'&savePath='+savePath,'files','width=100,height=50',false);
}

function Global_DeleteOption(controlName, isOppenr)
{
	var obj;
	
	if(isOppenr)
	{
		obj = opener.document.all[controlName];
	}
	else
	{
		obj = document.all[controlName];
	}

	obj.remove( obj.selectedIndex );

	self.close();
}

function Global_BindFileList(controlName, hiddenContolName)
{
    var control = FindObject(controlName);
    
	if(control !=null)
	{
		// 첨부파일을 리스트를 보냅니다.
		var files = '';
		
		var options = control.options;
		
		for(var i=0;i<options.length;i++)
		{
			files += "/"+options[i].text +"#" + options[i].value;
		}
		
		document.all[hiddenContolName].value = files;
		
	}
	
	return true;
	
}
