var ie6 = false;
var ie7 = false;
var ff = false; 
 
/**
 * 브라우저 버전 확인
**/
if(navigator.appName.indexOf("Microsoft") > -1 ){         
	// 익스플로러이면 버전 6인지 확인
	if( navigator.appVersion.indexOf("MSIE 6") > -1){
		ie6 = true;
	// 익스 플로러이면 버전 7인지 확인   
	}else if(navigator.appVersion.indexOf("MSIE 7") > -1){
		ie7 = true;
	}
} else {
	ff = true;
} 
   

 function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
 }

 function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
 }


 /** 강의보기 팝업**/
 function f_openLecture(courseId, lectureId, accessDevice, isMobileVideo){   
	
	var	url = "/home/search/viewService.do?courseId="+courseId+"&lectureId="+lectureId+"&ad="+accessDevice+"&imv="+isMobileVideo;     
	var name = "lecturePop"; 

	if(accessDevice == "md"){					// mobile device 
		window.open(url);
	}else{	
		var win = window.open(url,name,"resizable=yes,scrollbars=no,width=1040,height=640"); 	
		win.focus();  
	}
	
	// f_closeLecturePop(1);    
 }   
  
 
 function f_openLecture2(prm){   
		
		var lectureId = prm;  
		var	url = "/home/search/viewService.do?lectureId="+lectureId;     
		var name = "lecturePop"; 

		var win = window.open(url,name,"resizable=yes,scrollbars=no,width=1040,height=640");  
		
	    win.focus();  
	 
	   // f_closeLecturePop(1);
	    
	    }  
 
  
 /** 강의차시 가져오기**/
 function f_getLectures(obj,kemId,flag){   
	
	jQuery.ajax({
		type: "POST",
		url: "/home/special/lectures.do",
		data: "kemId=" + kemId, 
		error : function(html){
		alert("강의 정보를 가져올 수 없습니다.");
		},
		success : function(msg){
			try{
				var lectureObj = eval("(" + msg + ")");
				if( lectureObj[0]["lectures"].length  > 1){  
					f_viewLectures(obj, lectureObj, kemId, flag);  // 차시가 1개 이상
				}else if( lectureObj[0]["lectures"].length  == 1){
					var lecture = lectureObj[0]["lectures"][0];  //차시가 1개
					var lectureId = lecture['id'];   
						f_openLecture2(lectureId);
				}else{ 
					    f_openLecture2(kemId);   // 차시가 없는 경우
				}
		    }
			catch (e) {
				location.href = "/home/search/kemView.do?kemId="  + kemId;
			}
			
		}
	});
}  
 
 /** 강의보기 레이어**/
 function f_viewLectures(obj, lectureObj, kemId, flag){ 
	    
		if(flag == 1){
			var container = document.getElementById('lecture_layer');  
		}else{ 
			var container = document.getElementById('lecture_layer2');  
		}
		
		if (container.style.display == 'block') {
		      return true;
		  } 
		 
		var verticalPositionValue = findPosY(obj) + obj.offsetHeight-1;
		var verticalPosition = 'top: ' + verticalPositionValue + 'px;';
		var horizontalPosition = 'left: '+ findPosX(obj)+ 'px;'; 
		 
		var numLectures = lectureObj[0]["lectures"].length; 
		
		var html = []; 
		 
		html.push('<dl class="view_cont">'); 
		html.push('<dd class="tit clearfix">');  
		if (numLectures > 0) {
		html.push('<strong><span>강의리스트(총'); 
		html.push(numLectures); 
		html.push('개)</span></strong>'); 
		html.push('<a href="#" onClick="f_closeLecturePop('); 
		html.push(flag); 
		html.push('); return false;"><img src="/home/images/common/close_btn.gif" alt="close"/></a>'); 
		html.push('</dd>'); 
		html.push('<dd class="cont">');  
		if(numLectures < 11){ 
		html.push('<div class="view_cont_scroll_box">'); 	
		}else{
		html.push('<div class="view_cont_scroll_box2">');  
		}
		html.push('<ul class="view_list">'); 
		 
		if (numLectures > 0) {
			for (var i = 0; i < numLectures; i++) {
				var lecture = lectureObj[0]["lectures"][i];
				var index = i + 1;
				 
				var loc ='"'+lecture['location']+'"';   
				var lectureId = lecture['id'];   
				var errmsgTypeCode = lecture['errmsgTypeCode'];
				var msg = "강의바로보기";  
				var fulltitle = lecture['title']; 
				var title = lecture['title'];
					if (title.length > 24) {
						title = title.substring(0, 24) + '...';
					 } 
					 html.push('<li><span id="lecture');
					 html.push(index);
					 html.push('" style="background-color:#EA6408; color:#FFFFFF">');
					 html.push(index);
					 html.push('</span>'); 
				if(loc.indexOf("http://") > 0){	 
				html.push('<a  href="#Redirect" ');  
				html.push(' title="'+fulltitle + '" ');
				html.push(' onClick = "f_openLecture2(');  
				html.push(lectureId);
				html.push(');"');  
				html.push('>');  
				 var title = lecture['title'];
					if (title.length > 17) {
						title = title.substring(0, 17) + '...';
					}
				html.push(title); 
				html.push('</a></li>');
				}else{  
					html.push('<a');  
					html.push(' title="'+fulltitle + '" ');
					html.push('>');  
					 var title = lecture['title'];
						if (title.length > 17) {
							title = title.substring(0, 17) + '...';
						}
					html.push(title); 
					html.push('</a></li>');
					
				}
			  }	
			 }  
		 
		    html.push('</ul></div></dd></dl>'); 
			container.innerHTML = html.join('');
			
			container.style.display = 'block'; 
			container.style.top = verticalPositionValue + 'px';
			container.style.left = (findPosX(obj) - container.offsetWidth + obj.offsetWidth) + 'px';
			container.style.height = 'auto'; 
			container.style.visibility = 'visible';		
		}
	}
    
 /** 강의보기 close**/
 function f_closeLecturePop(flag) {
 	 
	 if(flag == 1){
 			var container = document.getElementById('lecture_layer');  
 	  }else{ 
 			var container = document.getElementById('lecture_layer2');  
 	  }
 		 
 	 container.innerHTML = '';
 	 container.style.display = 'none';
 }
 
/** 사용자, 강의별 카운트 **/ 
function f_mylistCount(obj,kemId,flag)  {   
	
	jQuery.ajax({
			type: "POST",
			url: "/home/mylist/searchMylistCount.do",
			data: {kemId : kemId},
			error : function(html){ 
	           
			},
			success : function(transport){  
					if(transport == "1"){
						if(confirm("이 강의는 이미 MY LIST에 담겨있습니다.\nMY LIST로 이동하시겠습니까?")){   
							document.location.href = "/home/mylist/mylist.do"; 
						}	
						
					}else{  
						if(flag == 3){    
							f_viewMylist_search(obj,kemId,flag); 
						}else{
						f_viewMylist(obj,kemId,flag);  
						}
					} 
			}
		}); 
}
 
 /** mylist 레이어**/
 function f_viewMylist(obj,kemId,flag){    
	 
  
	if(flag == 1){  
		
		var container = document.getElementById('mylist_layer');  
	}else{ 
		var container = document.getElementById('mylist_layer2');  
	}
	
	if (container.style.display == 'block') {
	      return true;
	  } 
	
	var verticalPositionValue = findPosY(obj) + obj.offsetHeight-1;
	var verticalPosition = 'top: ' + verticalPositionValue + 'px;';
	var horizontalPosition = 'left: '+ findPosX(obj)+ 'px;';  
	 
	var html = [];   
	  
	html.push('<form name=fm>');
	html.push('<dl class="view_cont">'); 
	html.push('<dd class="tit clearfix">');   
	html.push('<strong><span>MY LIST 담기</span></strong>');
	html.push('<a href="javascript:f_closeMylistPop('); 
	html.push(flag);
	html.push(');"><img src="/home/images/common/close_btn.gif" alt="close"/></a>'); 
	html.push('</dd>');
	html.push('<dd class="scrap">'); 
	html.push('<ul class="scrap">');
	html.push('<li>메모 <input type="text" name="memo_text"/></li>');		 
	html.push('<li class="btn"><a href="#" onclick="f_createMylist('); 
	html.push(kemId);  
	html.push(','); 
	html.push(flag); 
	html.push(');"><img src="/home/images/common/ok_btn.gif" alt="확인"/></a></li>');		 
	html.push('</ul></dd></dl>'); 
	html.push('</form>');  
	 
	container.innerHTML = html.join('');
	container.style.display = 'block'; 
	container.style.top = verticalPositionValue + 'px';
	container.style.left = (findPosX(obj) - container.offsetWidth + obj.offsetWidth) + 'px';
 }  
  
 /** mylist 레이어(통합검색)**/
 function f_viewMylist_search (obj,kemId,flag){   
	   
	    var container = document.getElementById('mylist_layer_search');  
	
	    if (container.style.display == 'block') {
		      return true;
		  } 
		
		var verticalPositionValue = findPosY(obj) + obj.offsetHeight-1;
		var verticalPosition = 'top: ' + verticalPositionValue + 'px;';
		var horizontalPosition = 'left: '+ findPosX(obj)+ 'px;';  
		 
		var html = [];   
		  
		html.push('<dl class="view_cont">'); 
		html.push('<dd class="tit clearfix">');   
		html.push('<strong><span>MY LIST 담기</span></strong>');
		html.push('<a href="javascript:f_closeMylistPop('); 
		html.push(flag);
		html.push(');"><img src="/home/images/common/close_btn.gif" alt="close"/></a>'); 
		html.push('</dd>');
		html.push('<dd class="scrap">'); 
		html.push('<ul class="scrap">');
		html.push('<li>메모 <input type="text" name="memo_text"/></li>');		 
		html.push('<li class="btn"><a href="#" onclick="f_createMylist_search('); 
		html.push(kemId);  
		html.push(','); 
		html.push(flag); 
		html.push(');"><img src="/home/images/common/ok_btn.gif" alt="확인"/></a></li>');		 
		html.push('</ul></dd></dl>'); 
		
		container.innerHTML = html.join('');
		container.style.display = 'block'; 
		container.style.top = verticalPositionValue + 'px';
		container.style.left = (findPosX(obj) - container.offsetWidth + obj.offsetWidth) + 'px';
	 } 
    
 /** mylist 담기**/
 function f_createMylist(kemId,flag) { 
	 var f= document.fm; 
	 var memoText = f.memo_text.value;   
	  
	 // if (user.isUserLogin()){ // 한 user 만 등록가능
	 jQuery.ajax({
			type: "POST",
			url: "/home/mylist/createMylist.do",
			data: {kemId : kemId ,
			       memoText : memoText 
	              },
			error : function(html){ 
	            	  
			alert("myList 추가에 실패하였습니다.");
			},
			success : function(msg){  
				if(msg == "success"){
					if(confirm("이 강의는 MY LIST에 담기 완료하였습니다.\nMY LIST로 이동하시겠습니까?")){ 
						document.location.href = "/home/mylist/mylist.do"; 
					}
					f_closeMylistPop(flag);
				}else{alert("myList 추가에 실패하였습니다."); 
					f_closeMylistPop(flag); 
				 }	
			 }
			  
		});  
    } 
   
 /** mylist 담기(통합검색)**/
 function f_createMylist_search(kemId,flag) { 
	 var f= document.searchFrm; 
	 var memoText = f.memo_text.value;   
	  
	 // if (user.isUserLogin()){ // 한 user 만 등록가능
	 jQuery.ajax({
			type: "POST",
			url: "/home/mylist/createMylist.do",
			data: {kemId : kemId ,
			       memoText : memoText 
	              },
			error : function(html){ 
	            	  
			alert("myList 추가에 실패하였습니다.");
			},
			success : function(msg){  
				if(msg == "success"){
					if(confirm("이 강의는 MY LIST에 담기 완료하였습니다.\nMY LIST로 이동하시겠습니까?")){ 
						document.location.href = "/home/mylist/mylist.do"; 
					}
					f_closeMylistPop(flag);
				}else{alert("myList 추가에 실패하였습니다."); 
					f_closeMylistPop(flag); 
				 }	
			 }
			  
		});  
    }
  
 /** mylist close**/
 function f_closeMylistPop(flag) {
 		
 		if(flag == 1){
 			var container = document.getElementById('mylist_layer');  
 		}else if(flag == 2){ 
 			var container = document.getElementById('mylist_layer2');  
 		}else{ 
 			var container = document.getElementById('mylist_layer_search');  
 		}
 		
 		container.innerHTML = '';
 		container.style.display = 'none';
 		
 } 	
 
 /** 로그인 팝업창 **/   
	function f_loginPopup(){    
		
		var returnUrl = location.href; 
		var	url = "/home/loginPop.do?returnUrl="+returnUrl; 
		var name = "loginPop"; 
		var win = window.open(url,name,"resizable=yes,scrollbars=no, width=540,height=320"); 
	}	 
	
	
/**내용바로보기**/	
	function player_goPos(no)
	{ 					
		/* MediaPlayer.controls.currentPosition = no;*/
		try{
			if(navigator.userAgent.indexOf("MSIE") != -1) { 	
				document.getElementById("MediaPlayer2").controls.currentPosition = no;  
			}else{	
				document.getElementById("MediaPlayer").controls.currentTime = no;  

			}		
		}  
	    catch(error) {
	       // alert(error);
		} 						
	}
	
/** 콘텐츠 퍼가기 **/
/** txt_content, dd_content **/
	function f_content(location,courseId,lectureId,contentType){    
		var location1=""; 
		var location2="";

		if(location.length >= 36 ){ 
			location1 = location.substring(0,36);  
			location2 = location.substring(36,location.length); 
			
			jQuery("#txt_content").text('<embed src="'+location1+'\n' 
                                        +location2+'" \n' 
                                        +'AutoStart="1" ShowTracker="1" \n' 
                                        +'ShowControls="true" ShowGotoBar="false" \n' 
                                        +'ShowDisplay="0" ShowStatusBar="1" \n' 
                                        +'AutoSize="true" pluginspage="http://www.microsoft.com/ \n' 
                                        +'windows/windowsmedia/download/" \n' 
                                        +'width="550px" height="480px"/>\n' 
                                        +'<div><img src="http://www.kocw.net/home/\n' 
                                        +'images/popup/kocw_banner.gif"/>'
                                        +'<iframe src="http://www.kocw.net/home/search/updateContentDown.do?courseId='+courseId
                                        +'&lectureId='+lectureId+'&contentType=1&userId=embed" width=0 height=0 />'
                                        +'</div>' 
									).select();
		}
       jQuery("#dd_content").show();   

        // 클립보드로 복사 
		var txt = jQuery("#txt_content").text();   
		var f = document.frm;       
		f.txt_content.value=txt.split('\n').join(""); 
		var doc = f.txt_content.createTextRange(); 
		f.txt_content.select(); 
		doc.execCommand('copy');  
		alert("콘텐츠 소스가  복사 되었습니다."); 
			
	}  

	function f_content_close(){  
		jQuery("#dd_content").hide();
	}		
	
	
	
	/*------------------------------------------------------------------
	 * 쿠키값 가져오기
	 *-----------------------------------------------------------------*/
	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 setCookie( name, value, expiredays ) {			
		var todayDate = new Date();
		todayDate.setDate( todayDate.getDate() + expiredays );
		document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
	}
	
	 /** 동영상 이어보기 **/
	 
	 var lecKemId4Cookie ;
	 
	 function do_WMP_status(NewState,lecKemId){	

			var WMP=new Object();
			var tid ;
			lecKemId4Cookie = lecKemId;

			if(navigator.userAgent.indexOf("MSIE") != -1) { 					

				if(NewState=='1'){
					clearInterval(tid);				
				}
				if(NewState=='3'){
					setInterval('setPlayTime()',2000); 				// 2초 마다 갱신
				}
			}
	}
	 
	// http://msdn.microsoft.com/en-us/library/bb249361(VS.85).aspx
	/*    var PlayStates = {
	       0: "Undefined", // Windows Media Player is in an undefined state.
	       1: "Stopped", // Playback of the current media item is stopped.
	       2: "Paused", // Playback of the current media item is paused. When a media item is paused, resuming playback begins from the same location.
	       3: "Playing", // The current media item is playing.
	       4: "ScanForward", // The current media item is fast forwarding.
	       5: "ScanReverse", // The current media item is fast rewinding.
	       6: "Buffering", // The current media item is getting additional data from the server.
	       7: "Waiting", // Connection is established, but the server is not sending data. Waiting for session to begin.
	       8: "MediaEnded", // Media item has completed playback.
	       9: "Transitioning", // Preparing new media item.
	      10: "Ready", // Ready to begin playing.
	      11: "Reconnecting" // Reconnecting to stream.
	    };
	*/ 

	function setPlayTime(){
		ctime = document.getElementById("MediaPlayer2").controls.currentPosition;	
		if(ctime > 30){
			setCookie('kocwVPosition_'+lecKemId4Cookie,ctime,180);  			
		}
	}

	function parseTime(value){

		value = value+"" ;
		value = value.substring(0, value.indexOf("."));
		value = value*1;

		hval = "00:";
		mval = "00:";

		if (value >= 3600)
		{
			hval = parseInt(value/3600)+":" ; 
			if(hval.length<3)		
				hval = "0"+hval;
			value = (value%3600);
		}
		if( value>=60 ){
			mval = parseInt(value/60)+":" ;
			if(mval.length<3)		
				mval = "0"+mval;
			value = (value%60);
		}
		if( value < 60 ){
			sval = value+"";
			if(sval.length<2)		
				sval = "0"+sval;			
		}

		return hval+mval+sval;
	}
	

	function seekPrePosition(lecKemId){	

		if(navigator.userAgent.indexOf("MSIE") != -1) {
			var ptime = getCookie('kocwVPosition_'+lecKemId)*1 ;   							

			if( ptime > 30 ) {																// 30초 이상 본 적이 있는 경우
				document.getElementById("MediaPlayer2").controls.pause();
				var answer = confirm('전에 보았던 강의입니다. ['+parseTime(ptime)+']부터 이어서 보시겠습니까?');
				if(answer==true){			
					document.getElementById("MediaPlayer2").controls.currentPosition = ptime-10 ;
					document.getElementById("MediaPlayer2").controls.play();
				}else{
					document.getElementById("MediaPlayer2").controls.play();
					setCookie('kocwVPosition_'+lecKemId,0,30);				// 취소 선택시 재생정보 삭제									
				}
			}else{
				document.getElementById("MediaPlayer2").controls.play();
			}
		}

	}
	
	 
	 
