
$(document).ready(function() {
	// 테이블 홀수행 색변환하기
	//$(".file_box tbody tr:even").addClass("odd");
	overEffect(".file_box tbody tr");
	createChild(".file_box td");
	createChild(".file_box th");

	//로그인박스 선택시 select
	$("#userid").click( function() { $(this).select(); });
	
	// 메뉴 오픈효과
	if(window_popup == 'no') {
		$('#gnb ul').superfish({ 
			delay:       500,                             // .5 second delay on mouseout 
			animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
			speed:       'fast',                          // faster animation speed 
			autoArrows:  false,                           // disable generation of arrow mark-up 
			dropShadows: false                            // disable drop shadows 
		}); 
	}

	//토글기능
	$(".tab").find("a").click(function() {
		tabToggle(this);
		return false;
	});
	function tabToggle(link) {
		var target = $(link).attr("href");
		if(user_type == 'guest' && target=='#send_sms'){
			alert('비회원은 사용할수 없는 기능입니다!!');
			return false;
		}
		$(".tab").find("li").removeClass("selected");
		$(link).parent().addClass("selected");
		var targetSiblings = $(target).attr("class");
		if ($(target).attr("class")) $("."+$(target).attr("class")).hide();
		$(target).show();
	}
});

function check_ssl_btn()
{
	if( $('#chk_ssl').attr('checked') )
		$('#chk_ssl').attr('checked','');
	else
		$('#chk_ssl').attr('checked','true');
}

window.logoutAct = function() {
	// 로그아웃 처리
	$.ajax( {
		type		: "POST",
		url			: "/login/logout.php",
		data		: "tmp="+new Date(),
		async		: true,
		success		: function(data) {
			var oj = new String();
			oj = data.split("|");
			//요구사항 으로 알림창 없앰 
			//alert(oj[0]);
				if(oj[1] ){ document.location.href=oj[1]; }
				else { document.location.href='/'; }
		},
		error : function(data) {
			alert("로그인시스템 오류입니다.");
		}
	});
}


window.loginAct = function() {
	// 로그인 처리
	
	
	var sUrl = new String();
		if(  !$("#userid").val() ) {
			alert('아이디가 입력되지 않았습니다!');
			$("#userid").select()
			return false;
		}

		if(  !$("#passwd").val() ) {
			alert('비밀번호가 입력되지 않았습니다');
			$("#passwd").select()
			return false;
		}
		 
   
	/*
	if(document.head_login.chk_ssl.checked == true){
	
		sUrl =  "https://www.filenavi.com";
	}else
	{
		sUrl = "http://www.filenavi.com";
	}
	
	*/
	//document.head_login.submit();
	
	
	
	     
	$.ajax( {
		type	: "POST",
		url		: "/login/act.php",
		data	: "userid="+ $("#userid").val() + "&passwd=" + $("#passwd").val() + "&url=" + $("#url").val(),
		async	: true,
		success : function(data) {
			var oj = new String();
			oj = data.split("|");
			if(oj[0] == 99) {
				alert(oj[1]);
				if(oj[2]) {
					$("#"+oj[2]).select();
				}
			} else {
				if(oj[1] ){ document.location.href=oj[1]; }
				else { document.location.href='/'; }
			}
		},
		error : function(data) {
			alert("로그인시스템 오류입니다.");
		}
	});
	return false;
	

}

window.error = function(elem,val) {
	alert(val);
	elem.focus();
}

// IE fisrt-child, last-child 생성
function createChild(elem) {	
	if (!$.browser.msie) return false; 
	$(elem+":first-child").addClass("first-child");
	$(elem+":last-child").addClass("last-child");
}

// hover 이벤트
function overEffect(elem) {
	if (!$.browser.msie) return false;
	if ($.browser.version > 6.0) return false;
	$(elem).hover(
		function(){
			$(this).addClass("over");
		},function(){
			 $(this).removeClass("over");
		}
	);
}

 // Ajax Call 이 시작될때 호출되는 함수
$().ajaxSend(function() {   
	$("#contentLoading").show();
});   
  
// Ajax Call 이 끝날때 호출되는 함수
$().ajaxStop(function() {
	$("#contentLoading").fadeOut("fast");   
});   

// Ajax 쪽지 불러오기
function memo_get_ajax(){	
	$.post('/note/note.php', function(data){
		if(data == 1){
			$('#note_new').html('<img src="/images/main6/ico_new.gif" alt="new" />');
		}else{
			$('#note_new').html('');
		}
	});
}



//트림 함수좌우 공백 제거
function trim(s) {
  s += ''; // 숫자라도 문자열로 변환
  return s.replace(/^\s*|\s*$/g, '');
}

// 전송하고자 하는 메세지의 바이트수를 체크한다.
var longMsgStatus		= false;
var hangulStatus		= false;

function msgByteLength()
{
	var str,msg;
	var len = 0;
	var temp;
	var count = 0;
	msg = document.sms_form.Message.value;
	str = new String(msg);
	len = str.length;
	for (k=0 ; k<len ; k++) {
		temp = str.charAt(k);
		if (escape(temp).length > 4) {
			count += 2;
			//hangulStatus 	= true;
		} else if (temp == '\r' && str.charAt(k+1) == '\n') {
			count += 2;
			//hangulStatus 	= false;
		} else if (temp != '\n') {
			count++;
			//hangulStatus 	= false;
		}
		//window.status = "LOOP : "+ k +", COUNT : "+ count +", ESCAPE : "+ escape(temp) +", ESCAPE LENGTH : "+ escape(temp).length +", HANGUL STATUS : "+ hangulStatus +", LENGHT : "+ len;
		//window.status = "ESCAPE : "+ escape(temp) +", ESCAPE LENGTH : "+ escape(temp).length +", HANGUL STATUS : "+ hangulStatus +", LENGHT : "+ len;
	}
	return count;
}

//SMS보내기 문자 길이 체크
function checkMsg() {
	var count= msgByteLength();
	document.sms_form.msgLen.value	= count;
	if(count > 80) {
		document.sms_form.Message.blur();
		document.sms_form.Message.focus();
		alert("메시지 내용은 80바이트까지만 전송이 가능합니다.");
		CutChar();
	}
}



//SMS보내기 문자 길이 체크

function checkSsl(rurl) {
	var chk = document.head_login.chk_ssl;
	 /*
		
	if(document.head_login.chk_ssl.checked == true){
		document.head_login.action =  "https://www.filenavi.com"+rurl;
		
	}else
	{
		document.head_login.action = "http://www.filenavi.com" +rurl;
			
	}
	*/
	
	
	return ;
}	


	
// 지정된 바이트가 초과경우 문자를 삭제한다.
function CutChar()
{
	var str,msg;
	var len=0;
	var temp;
	var count;
	count = 0;

	msg = document.sms_form.Message.value;
	str = new String(msg);
	len = str.length;

	for(k=0 ; k<len ; k++)
	{
		temp = str.charAt(k);

		if(escape(temp).length > 4) {
			count += 2;
		} else if(temp == '\r' && str.charAt(k+1) == '\n') {
			count += 2;
		} else if(temp != '\n') {
			count++;
		}

		if(count > 80) {
			str = str.substring(0,k);
			break;
		}
	}
	document.sms_form.Message.value = str;
	checkMsg(str);
}

//주소록 삭제
function addr_del() {
		var del_data = new Array();
		var chk = document.getElementsByName('check[]');

		for (var i = 0; i < chk.length; i++) {	
			if(chk[i].checked == true){
				var del_num  = $(chk[i]).val();
				del_data.push(del_num);
			}
		}//end for

	if(del_data.length == 0){
		alert('삭제할 주소를 선택하세요!!');
		return;
	}

	var del_con = confirm('정말 삭제 하시겠습니까?');
	if(del_con == true){
		//삭제파일 ajax전송
			$.post ('/addr_book/addr_del.php',  {'del_files[]' : del_data}, function(data){
//					alert(data);
					document.location.reload();
			});//end post
	}//end if

}

//보낸편지함 삭제
function email_history_del() {
		var del_data = new Array();
		var chk = document.getElementsByName('check[]');

		for (var i = 0; i < chk.length; i++) {	
			if(chk[i].checked == true){
				var del_num  = $(chk[i]).val();
				del_data.push(del_num);
			}
		}//end for

	if(del_data.length == 0){
		alert('삭제할 항목을 선택하세요!!');
		return;
	}

	del_con = confirm('정말 삭제 하시겠습니까?');
	if(del_con == true){
		//삭제파일 ajax전송
			$.post ('/email_history/email_history_del.php',  {'del_files[]' : del_data}, function(data){
//					alert(data);
					document.location.reload();
			});//end post
	}//end if
}


 /* member - note */
function note_view(n)	{
	document.getElementById( "note_title1" ).className = '';
	document.getElementById( "note_title2" ).className = '';
	document.getElementById( "note_list1" ).className = 'noscreen';
	document.getElementById( "note_list2" ).className = 'noscreen';
	document.getElementById( "note_title"+n ).className = 'selected';
	document.getElementById( "note_list"+n ).className = ''; 	
}


//쪽지 보내기
function sendMemo() {
	var memos = window.open("about:blank", "memos", "width=400,height=470,scrollbars=no"); 
	memos.location.href = "/note/send.php"; 
	memos.focus();
}

//쪽지 읽기
function readMemo(types,num) {
	var memos = window.open("about:blank", "memos", "width=400,height=470,scrollbars=no"); 
	memos.location.href = "/note/view.php?types="+types+"&num="+num; 
	memos.focus();
}

//쪽지 삭제
function delMemo(chk_num) {
	var del_con = confirm('정말 삭제 하시겠습니까?');
	if(del_con == true){
			var del_data = new Array();
			var chk = document.getElementsByName('chk[]');
			for (var i = 0; i < chk.length; i++) {	
				if(chk[i].checked == true){
					var del_num = $(chk[i]).val(); //삭제할 num추출
					del_data.push(del_num);
				}
			}//end for

		if(del_data.length == 0){
		alert('삭제할 항목을 선택하세요!!');
		return;
		}

		//삭제파일 ajax전송
			$.post ('/note/note_del.php',  {'del_files[]' : del_data, 'flag' : chk_num}, function(data){
//					alert(data);
					document.location.reload();
			});//end post
	}//end if
}

//벨리데이션 체크
//val의 첫번째는 폼네임 그외는 필드명
//ex) onsubmit="return Chk_addr('Addr_Form||user_name||user_email||user_hp')" 식으로 함수 호출
//에러 출력할 #Addr_Div는 경우에 맞게 수정
function Chk_form(val) {
	var val_array = new Array();
	var formChecks = new Array();
	val_array =  val.split("||");
	var form = "document."+val_array[0];

	for(var i=0; i<val_array.length-1; i++) {
		formChecks[i] = val_array[i+1];
		var chkF = eval(form+'.'+formChecks[i]);

		if(chkF.tagName == "INPUT") {
			if(!chkF.value) {
				alert(chkF.title+'(을)를 입력해주세요!!');
//				$("#Addr_Div span").text(chkF.title+'(을)를 입력해주세요').show().fadeOut(1000);
				chkF.focus();
				return false;
			}
		}else if(chkF.tagName == "SELECT") {
			if(!chkF.value) {
				alert(chkF.title+'(을)를 선택해주세요!!');
//				$("#Addr_Div span").text(chkF.title+'(을)를 선택해주세요').show().fadeOut(1000);
				chkF.focus();
				return false;
			}
		}else if(chkF.tagName == "CHECKBOX"){
			if(!chkF.checked == true){
				alert('최소한 하나를 선택해주세요!!');
				return false;
			}
		}else if(chkF.tagName == "RADIO"){
			if(!chkF.checked == true){
				alert('최소한 하나를 선택해주세요!!');
				return false;
			}
		}
	}//end for
}




//전체 체크 플러그인 펑션
jQuery.fn.extend({
	check: function() {
	 return this.each(function() { 
		 this.checked = true; 
		 });
	},
	uncheck: function() {
	 return this.each(function() { 
		 this.checked = false; 
		 });
	}
});


//전체 체크 실행 함수
$(function(){
   $(".Chk_button").toggle(
		function(){
		$('input').check();
		$(".files").addClass("filesele");
//		$(".Chk_button").text("전체해제");
		
	},
		function(){
		$('input').uncheck();
		$(".files").removeClass("filesele");
//		$(".Chk_button").text("전체선택");
	});
});

//로그인 텍스트 효과 함수
$(function(){
	$("#login .form_text").focus( function() {
		$(this).addClass("focus");
	});
	$("#login .form_text").blur( function() {
		if ( this.value.length==0 ) $(this).removeClass("focus"); 
	});

	$("#login .form_text").each(function(){
		if($(this).val()){
				$(this).addClass("focus");
		}
	});
});



//파일 삭제 펑션
function file_delete(access_key) {
	var del_file = new Array();
	var del_data = new Array();
	var split_data = new Array();
	var del_dom_num = new Array();
	var chk = document.getElementsByName('check[]');

	for (var i = 0; i < chk.length; i++) {	
		if(chk[i].checked == true){
			var idx_num = $(chk[i]).parent().parent().attr('idx'); //idx넘버 추출
			del_file[i] = $(".filename"+idx_num).find('input:hidden').val();
			del_dom_num.push(idx_num);
			del_data.push(del_file[i]);
		}
	}//end for

	if(del_data.length == 0){
		alert('삭제할 파일을 선택하세요!!');
		return;
	}

	//삭제할 파일 ajax 전송
	$.post("/file_delete.php", { 'del_files[]' : del_data  }, function(data){
		//콜백이 "OK" 이면 정상 , "FAIL"이면 오류
		//OK이면 DOM 삭제
		if(trim(data) == 'OK'){
			for(var i=0 ; i<del_dom_num.length; i++){
				$('#fileListbody').find('tr[idx='+del_dom_num[i]+']').each(function(){
						$(this).fadeOut('medium', function(){
								$(this).remove();
						});//end fadeOut
				});//end each					
				file_old_nums--; //선택된 파일갯수 감소
			}
//				movie.run();
		}else{
			alert('파일 삭제 실패!!');
		}
	});

}



//Global Navigation Bar
/*
$(function(){
	var gnb = ("#gnb");
	$(gnb).children("ul").children("li").each( function() {
		var item = $(this);
		//mouse Action
		$(item).hover( function() {
			$(item).children("ul").slideDown("fast");
		}, function() {
			$(item).children("ul").slideUp("fast");
		});
		//keyboard Action
		$(item).children("a").focus( function() {
			$(item).children("ul").slideDown();
		});
		$(item).children("ul").children("li").children("a:last").blur( function() {
			$(item).children("ul").slideUp();
		});
	});
});
*/

//Global Navigation Bar 설정
$(function(){
	//Depth2 width 설정
	$("#gnb>ul>li").each( function() {
		var width =	$(this).width();
		$(this).children("ul").width($(this).width()+1);
	});
	//Depth1 first-child
	$("#gnb>ul li:first").addClass("first");
});




//팝업 띄우기
function popup(url,name,val){
//	 var popup = window.open("about:blank",name,val); 
	 var popup = window.open(url,name,val); 
	 popup.location.href = url; 
	 popup.focus();
	 setTimeout('url_add_form()', 700); // 0.7초후 url_add_form 호출
}




//바탕화면 바로가기 아이콘 만들기
function create_icon() {
	var desktop = google.gears.factory.create('beta.desktop');
	desktop.createShortcut('FileNavi',
						   'http://www.filenavi.com/index.php?icon=yes',
						   {
							  '128x128': '/images/icon128.png',
							  '48x48': '/images/icon48.png',
							  '32x32': '/images/icon32.png',
							  '16x16': '/images/icon16.png'
							},
						   '파일나비 바로가기 http://www.filenavi.com/index.php?icon=yes');	
}

//sms 삭제
function sms_history_del(){
		var del_data = new Array();
		var chk = document.getElementsByName('check[]');

		for (var i = 0; i < chk.length; i++) {	
			if(chk[i].checked == true){
				var del_num  = $(chk[i]).val();
				del_data.push(del_num);
			}
		}//end for

	if(del_data.length == 0){
		alert('삭제할  항목을 선택하세요!!');
		return;
	}

	var del_con = confirm('정말 삭제 하시겠습니까?');
	if(del_con == true){
		//삭제파일 ajax전송
			$.post ('/sms/sms_del.php',  {'del_files[]' : del_data}, function(data){
//					alert(data);
					document.location.reload();
			});//end post
	}//end if
}


//클립보드 복사
function setClip(ids)
{
	var meintext = $(ids).prev().val();
	 if (window.clipboardData) 
		   {
		   	 
			   var a = window.clipboardData.setData("Text", meintext);
			   if(a){
				   alert('복사되었습니다!!');
			   }
		   }
	   else if (window.netscape) 
		   { 
				alert('익스플로어 전용메뉴입니다!!');
		   }
}

// 파일리스트
$(function(){
	var table = ".file_list table";
	$(table).find("th:first").addClass("first");
	$(table).find("th:last").addClass("last");
});


function tooltip(target) {
	var elem = $(target);
	if ( elem.css("display") != "none" ) {
		elem.fadeOut();
		elem.parent().css("z-index","10")
	} else {
		elem.parent().css("z-index","20")
		elem.fadeIn();
	}
}




//선물내역 탭선택
function tab_selec(tab_num) {
	document.location.href='/mypage/doc.php?tkind=1&lkind=28&tab='+tab_num;
}

//쪽지함 탭선택
function tab_selec_note(tab_num) {
	document.location.href='/mypage/doc.php?tkind=1&lkind=37&tab='+tab_num;
}

window.forget = function() {
	// 아이디/비밀번호 찾기
	var itemPOP = window.open("about:blank", "itemPOP", "toolbar=no,location=no,directories=no,status=yes,menubar=no,resizable=no,width=400,height=400,scrollbars=yes"); 
	itemPOP.location.href = "/login/forget.php"; 
	itemPOP.focus();
}
