
//input onfocus 시 value 초기화
function clearText(input){
	input.value="";
};


//팝업
function openWindow(href,width,height){
	if(width == null){
		width ="400";
	};
	if(height == null){
		height ="150";
	};
	window.open(href,"child","scrollbars=yes,width="+width+",height="+height);
};

//주민번호 체크 하면서 폼체크
function formSubmitCkJumin(form){
		
		var el = form.elements;
		var elNumber = eval(form.elements.length);

		for(i=0;i<elNumber;i++){
			if(el[i].getAttribute('REQUIRED')|| el[i].getAttribute('REQUIRED') != null){
				switch(el[i].tagName){
					case "TEXTAREA" :
					case "INPUT" :
						if(el[i].value==null || el[i].value==""){
							alert(el[i].getAttribute('hname')+"를 입력해주세요");
							el[i].focus();
							return false;
						};
						break;

					case "select-one" :
						if(el[i].selectedIndex == '0'){
							alert(el[i].getAttribute('hname')+"를 선택해주세요");
							el[i].focus();
							return false;
						};
						break;

				};
			};
		};
		var juminCk = jumin_check(form);
		if(juminCk == false || juminCk == null){
			alert("잘못된 주민번호 입니다 확인해 주세요.");
			return false;
		};

};

//폼체크
function formSubmitCk(form){
		var el = form.elements;
		var elNumber = eval(form.elements.length);
		for(i=0;i<elNumber;i++){
			if(el[i].getAttribute('disabled') == false && el[i].getAttribute('REQUIRED') != null ){
				switch(el[i].tagName){
					case "TEXTAREA" :
					case "INPUT" :
						if(el[i].value==null || el[i].value==""){
							alert(el[i].getAttribute('hname')+"를 입력해주세요");
							el[i].focus();
							return false;
						};
						break;

					case "select-one" :
						if(el[i].selectedIndex == '0'){
							alert(el[i].getAttribute('hname')+"를 선택해주세요");
							el[i].focus();
							return false;
						};
						break;

				};
			};
		};
	
};
//폼체크
function formSubmitCk_test(form){
		var el = form.elements;
		var elNumber = eval(form.elements.length);
		for(i=0;i<elNumber;i++){
			if(el[i].getAttribute('disabled') == false && el[i].getAttribute('REQUIRED') != null ){
				switch(el[i].tagName){
					case "TEXTAREA" :
					case "INPUT" :
						if(el[i].value==null || el[i].value==""){
							alert(el[i].getAttribute('hname')+"를 입력해주세요");
							el[i].focus();
							return false;
						};
						break;

					case "select-one" :
						if(el[i].selectedIndex == '0'){
							alert(el[i].getAttribute('hname')+"를 선택해주세요");
							el[i].focus();
							return false;
						};
						break;

				};
			};
		};
	
};

//폼체크

function formSubmitCk_jquery(formName){

	$('form[name="'+formName+'"] input[required],form[name="'+formName+'"] textarea[required]').each(function(){
		if($(this).css("display")=='inline-block' && ($(this).val()=='' || $(this).val()==null)){
			hname = $(this).attr("hname");
			alert(hname+"을 입력해주세요");
			$(this).focus();
			return false;
		}
	});
	return true;

};

//주민번호 체크
function jumin_check(form) {
	var jumin =  document.getElementById("resno").value;
     if ( jumin.length != 13) 
     {   // 번호가 13개 아니라면
        document.getElementById("resno").focus(); //커서를 주민번호 앞자리에 놓는다.
      return false;
     } 
     else 
     {   
        var strjumin = jumin;  
      
     }
        var a1=strjumin.substring(0,1)   //주민번호 계산법
        var a2=strjumin.substring(1,2)          
        var a3=strjumin.substring(2,3)
        var a4=strjumin.substring(3,4)
        var a5=strjumin.substring(4,5)
        var a6=strjumin.substring(5,6)
        var checkdigit=a1*2+a2*3+a3*4+a4*5+a5*6+a6*7
        var b1=strjumin.substring(6,7)
        var b2=strjumin.substring(7,8)
        var b3=strjumin.substring(8,9)
        var b4=strjumin.substring(9,10)
        var b5=strjumin.substring(10,11)
        var b6=strjumin.substring(11,12)
        var b7=strjumin.substring(12,13)
        var checkdigit=checkdigit+b1*8+b2*9+b3*2+b4*3+b5*4+b6*5 
        checkdigit = checkdigit%11
        checkdigit = 11 - checkdigit
        checkdigit = checkdigit%10
        
        if (checkdigit != b7) 
        {   
           document.getElementById("jumin1").value="";
           document.getElementById("jumin2").value="";
           document.getElementById("jumin1").focus();   
           return false;
        } 

      return true;
}


//개체에 현재 위치값을 반환
function getRealOffsetTop(o) { return o ? o.offsetTop + getRealOffsetTop(o.offsetParent) : 0; } 
function getRealOffsetLeft(o) { return o ? o.offsetLeft + getRealOffsetLeft(o.offsetParent) : 0; } 


//confirm
function confirmCk(text,url,target){
	if(confirm(text)==true){
		if(target == "parent"){
			parent.window.location.href=url;
		}else{
			self.location.href=url;
		};
	}else{
		return false;
	};
	
};


//화면의 가운데정렬(가로)
function alignCenter(obj){
	halfClient = document.body.clientWidth	/2
	halfOffset = obj.offsetWidth/2;
	center = halfClient - halfOffset;
	return center;
};
//화면의 가운데정렬(세로)
function verticalCenter(obj){
	halfMiddle = document.body.clientHeight/2;


	halfOffsetMiddle = obj.offsetHeight/2;
	middle =halfMiddle  - halfOffsetMiddle;
	return middle;

};
//스크롤높이 구함. expression(verticalCenter(obj)+scroll())형식으로 해준다.
function scroll(){
	return document.body.scrollTop;
}

function email_sel(sel){
	document.getElementById("email_2").value = sel.options[sel.selectedIndex].value;
};


//(폼,최대글자,한글가능여부((y,n),영어가능여부(y,n),특수문자가능여부(y,n),숫자가능여부(y,n))
function wordCk(obj,max_length,kor,eng,spe,num){
	string =obj.value			//문자열
	stringLen = string.length  //문자열의 총길이
	stringByte = 0;				//계산될 바이트
	now_length = 0;				//계산될 문자열 길이
	limit_string = "";
//	alert(string);	
	pass = true;				//한글,영문,특수문자 체크하기 위한 변수
	if(stringLen ==0 ){
		limit_string = string;  //문자열이 없으면 문자열 그대로 반환
	}else{						//문자열이 있으면
		for(i=0;i<stringLen;i++){
			word = string.charAt(i); //한자리씩 문자 빼오기
			
		  if(kor == 'n'){
				pass = korCk(word,pass);
		  };
		  if(eng == 'n'){
				pass = engCk(word,pass);
		  };
		  if(spe == 'n'){
				pass = speCk(word,pass);
		  };
		  if(num == 'n'){
				pass = numCk(word,pass);
		  };
		  stringByte = stringByte + byteCk(word);	
			
			if(stringByte > max_length || pass==false){
				limit_string = string.substring(0,now_length);
				obj.value=limit_string;
				break;
			}
			now_length++;
		};
	};
}

function byteCk(word){
	ascii = word.charCodeAt(0);
	if(ascii > 122){
		return 2;
	}else{
		return 1;
	};
};
function korCk(word,pass){
	ascii = word.charCodeAt(0);
	if(ascii > 126 || pass==false){
		return false
	}else{
		return true
	};
};

function engCk(word,pass){
	ascii = word.charCodeAt(0);
	
	if((ascii > 64 && ascii < 123) || pass==false){
		return false
	}else{
		return true
	};
};

function speCk(word,pass){
	ascii = word.charCodeAt(0);
	if((ascii > 33 && ascii < 48) || (ascii > 57 && ascii < 65) || (ascii > 90 && ascii < 97) || ( ascii > 122 && ascii < 127) || pass==false){
		return false
	}else{
		return true
	};
};

function numCk(word){
	ascii = word.charCodeAt(0);
	if((ascii > 47 && ascii < 58) || pass==false){
		return false
	}else{
		return true
	};
};

function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);
   if (endstr == -1) endstr = document.cookie.length;
   return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;
   while (i < clen) {	//while open
      var j = i + alen;
      if (document.cookie.substring(i, j) == arg)
         return getCookieVal (j);
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0) break; 
   }	//while close
   return null;
}

 function setCookie( cookieName, cookieValue, expireDate )
 {
  var today = new Date();
  today.setDate( today.getDate() + parseInt( expireDate ) );
  document.cookie = cookieName + "=" + escape( cookieValue ) + "; path=/; expires=" + today.toGMTString() + ";";
 }






//해당 객체에 가운데 top 값
function centerTop(obj){
	scroll = document.body.scrollTop;
	height = document.body.clientHeight/2;
	objHeight = obj.offsetHeight/2;

	objTop = scroll+(height-objHeight);

	return objTop;
}

//해당 객체에 가운데 Left 값
function centerLeft(obj){
	width = document.body.clientWidth/2;
	objWidth = obj.offsetWidth/2;
	objLeft = width-objWidth;
	return objLeft;
}


//전체 체크 버튼검사해서 전체 체크 or 전체 해제
$("input[name=allCheck]").click(function(){
	if($(this).attr("checked") == true){
		$("input[name=chMember[]]").attr("checked",true);
	}else {
		$("input[name=chMember[]]").attr("checked",false);
	};
});



//달력
//달력만들기
function carendar(year,month){
	now_date = new Date(year,(month-1));//현재시간
	nYear = now_date.getFullYear(); //현재 년도
	nMonth = String(now_date.getMonth()); //현재 월
	disMonth = String(now_date.getMonth()+1); //현재 월
//	nDate = String(now_date.getDate());// 현재 날짜

	if(disMonth.length == 1)disMonth = "0"+disMonth;//월이 한자리면 앞에 0을 붙여준다.

	HTML ="";


	//해당월의 마지막날짜.
	cus_date = new Date(nYear,nMonth,0);//객체를 선언할때 날짜를 0으로 하면 전달의 마지막날이 반환된다.
	last_date = cus_date.getDate();
	//해당월의 1일이 해당하는 요일
	cus_date.setFullYear(nYear,nMonth,1);  //setFullYear이란 메소드는 해당 객체를 원하는 다른 날로 다시생성한다.
	first_day = cus_date.getDay();



	//HTML += "<div>"+nYear+"년 "+disMonth+"월</div>"
	HTML +="<table border='0' cellpadding='0' cellspacing='1' bgcolor='#cecece' id='diaryTable' style='color:#8E8C8F'>";
	HTML +="<tr bgcolor='#eeeeee' height='30' style='text-align:center;font-weight:bold;color:#8E8C8F'><td width='115' style='color:red'>일요일</td><td width='115'>월요일</td><td width='115'>화요일</td><td width='115'>수요일</td><td width='115'>목요일</td><td width='115'>금요일</td><td width='115' style='color:blue'>토요일</td></tr>";
	HTML +="<tr bgcolor='white' height='80' style='text-align:left;vertical-align:top;padding:3'>";
	var date=1; //화면에 노출될 날짜.
	var dayper=1; //줄바꿈을 해주기 위한 변수
	var ck = true;//반복복에서 빠져나오기 위한 변수

	while(ck==true){
		if(dayper%7==1)style="color:red";else if(dayper%7==0)style="color:blue";else style="";
		if(String(date).length == 1)disdate = "0"+date; else disdate = date;
		if(dayper<(first_day+1)){ //첫날의 반환값은 목요일이므로 4(0부터시작) dayper는 1부터 시작이므로 첫날+1이랑 같아지기전에는 공백만넣어라
			HTML +="<td>&nbsp;</td>";
		}else if(date <= last_date){ //첫날+1과 dayper가 같아지면 화면에 날수를 노출해라
			HTML +="<td  style='cursor:hand;padding-left:3px;padding-top:3px;"+style+"' date='"+nYear+disMonth+disdate+"' id='"+nYear+disMonth+disdate+"' "+style+" class='dateTd'><div>"+date+"</div><div id='planTotal'><span style='height:10px'></span></div><div id='planLayer"+nYear+disMonth+disdate+"'></div></td>";			
			date++;//date가 하나씩 커지면서 날짜를 계속 노출
		}else if(date > last_date && dayper%7 !=1){ //date가 커지다가 해당월에마지막날짜보다 커지면 다시 공란을 노출해라 단 공란은 그주의마지막 까지만!
			HTML +="<td>&nbsp;</td>";
		}else{//그주의 마지막 공란까지 노출했으면 반복문을 빠져나와라 혹은 ck=false 로 바꿔주어도 while문 조건문에 안맞아 빠져나온다.
			break;	
		};
		if(dayper%7==0 && date <= last_date)HTML +="</tr><tr bgcolor='white' height='80' style='text-align:left;vertical-align:top;padding:3'>"; //dayper가 커지다가 한주7일로 나누어 0이되면 줄바꿈하라.
		dayper++;//반복문 마지막에 dayper증가하라.

	};

	HTML +="</tr></table>";
return HTML
//달력만들기 끝
}


function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                return true;
            }
        }
    }
     return false;
} 

function post(temp)
{	
	if(temp == ''){
		return false;
	}
    window.open("/post.html?type="+temp,"","height=200,width=300,toolbar=no,scrollbars=yes,menu=no");
}


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(){
		$("#cookIdCheck").click(function(){
			user_id = $("#user_idInput").val();

			if($(this).attr("checked")==true){
				setCookie("idCookie",user_id,'86400');
			}else{
				setCookie("idCookie",user_id,0);
			}

		})
	});

function doSomething(e) { 

	if (!e) var e = window.event; 
	if (e.pageX || e.pageY) { 
		posx = e.pageX; 
		posy = e.pageY; 
	} else if (e.clientX || e.clientY) 
	{ 
		preposx = posx;
		preposy = posy;
		posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
	};
//	alert(posx+"::"+posy);
} 

var callSmsLayer = function(mobile,param){
	parameter = "";
	if(param != '')
		parameter = param;


	if(mobile != null && mobile!='' && mobile!='undefined')
		parameter += "&mobile="+mobile;
		
	$.ajax({
		url :"/auth/smsLayer.html",
		dataType : "html",
		data : parameter,
		type : "GET",
		success : function(data){
			$("#layerPop").html(data);
			topHeight = document.documentElement.scrollTop;
			$(window).bind("resize", function() {
				$("#layerPop").css("top", (topHeight+67)).css("left", (( document.body.clientWidth / 2)-150)).show();
			}).trigger("resize");
		}
	});
};

//-- 인자 textarea, byte표시 text필드, 제한byte
function textCounter(theField,tartheCharCounter,maxChars)
{
        var strCharCounter = 0;
        var intLength = theField.value.length;

        for (var i = 0; i < intLength; i++)
        {
                var charCode = theField.value.charCodeAt(i);
//한글일 경우
                if (charCode > 128)        {
                        strCharCounter += 2;
                } else {
                        strCharCounter++;
                }
				/*
                if(strCharCounter < (maxChars+1)) {
                        theCharCounter.value = strCharCounter;
                } else {
                        eval("alert('한글" + maxChars/2 + ", 영문" + maxChars+ "자 제한입니다. 초과된 문자는 잘립니다.')");
                        if(!cutStr(theField, i, theCharCounter, maxChars)) {
                                alert("문자열 커트 함수가 작동되지 않습니다.");
                        }
                        break;
                }*/
        }
		$("#"+tartheCharCounter).html(strCharCounter);

}


function loadUsreInfo(user_id){
	stat = $("#userInfoBox").css("display");

	topPos = window.event.clientY+document.documentElement.scrollTop;
	$.ajax({
		url : "/auth/3_member/loadUserAjax.html",
		dataType : "html",
		data :"user_id="+user_id,
		type :"get",
		success : function(data){
			$("#layerPop").html(data);
			$(window).bind("resize", function() {
				$("#layerPop").css("top", (topPos+20)).css("left", ( (document.body.clientWidth / 2)-400)).show();
			}).trigger("resize");
		}
	});
}

//return what kind of broswer
function whichBrs() 
{

  var agt = navigator.userAgent.toLowerCase();
  if (agt.indexOf("opera")        != -1) return 'Opera';
  if (agt.indexOf("staroffice")   != -1) return 'Star Office';
  if (agt.indexOf("webtv")        != -1) return 'WebTV';
  if (agt.indexOf("beonex")       != -1) return 'Beonex';
  if (agt.indexOf("chimera")      != -1) return 'Chimera';
  if (agt.indexOf("netpositive")  != -1) return 'NetPositive';
  if (agt.indexOf("phoenix")      != -1) return 'Phoenix';
  if (agt.indexOf("firefox")      != -1) return 'Firefox';
  if (agt.indexOf("safari")       != -1) return 'Safari';
  if (agt.indexOf("skipstone")    != -1) return 'SkipStone';
  if (agt.indexOf("msie 8")         != -1) return 'IE8';
  if (agt.indexOf("msie 7")         != -1) return 'IE7';
  if (agt.indexOf("msie 6")         != -1) return 'IE6';
  if (agt.indexOf("msie 9")         != -1) return 'IE9';
  if (agt.indexOf("netscape")     != -1) return 'Netscape';
  if (agt.indexOf("mozilla/5.0")  != -1) return 'Mozilla';
  if (agt.indexOf('\/')           != -1) 
  {
    if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') 
    {
      return navigator.userAgent.substr(0,agt.indexOf('\/'));
    }else 
      return 'Netscape';
  } else if (agt.indexOf(' ') != -1)
  {
    return navigator.userAgent.substr(0,agt.indexOf(' '));
  } else 
    return navigator.userAgent;
}


//외국인 체크
var chkForeign = function(){
	var fgn_reg_no = $('#foreign1').val() + $('#foreign2').val();; 

	if (fgn_reg_no == ''){ 
			alert('외국인등록번호를 입력하십시오.'); 
			return false; 
	} 

	if (fgn_reg_no.length != 13) { 
			alert('외국인등록번호 자리수가 맞지 않습니다.'); 
			return false; 
	} 
	if ((fgn_reg_no.charAt(6) == "5") || (fgn_reg_no.charAt(6) == "6")) 
	{ 
	   birthYear = "19"; 
	} 
	else if ((fgn_reg_no.charAt(6) == "7") || (fgn_reg_no.charAt(6) == "8")) 
	{ 
	   birthYear = "20"; 
	} 
	else if ((fgn_reg_no.charAt(6) == "9") || (fgn_reg_no.charAt(6) == "0")) 
	{ 
	   birthYear = "18"; 
	} 
	else 
	{ 
	  alert("등록번호에 오류가 있습니다. 다시 확인하십시오."); 
	  return false; 
	}         

	birthYear += fgn_reg_no.substr(0, 2); 
	birthMonth = fgn_reg_no.substr(2, 2) - 1; 
	birthDate = fgn_reg_no.substr(4, 2); 
	birth = new Date(birthYear, birthMonth, birthDate); 
	 
	if ( birth.getYear() % 100 != fgn_reg_no.substr(0, 2) || 
		 birth.getMonth() != birthMonth || 
		 birth.getDate() != birthDate) { 
		alert('생년월일에 오류가 있습니다. 다시 확인하십시오.'); 
	  return false; 
	} 
	alert('인증되었습니다.');
	$("#realName").val("pass");
	$("#resno").val(fgn_reg_no);
	//return true; 
}
