/**********************************************************************
*  2011 view page renewal .... 
*  by hyojung (적용일 2011.3.14)
***********************************************************************/
$(document).ready(function(){

		// 엠군내 유입인 경우 댓글 탭 활성화 But 댓글 카운트가 0인경우 상세정보탭 활성화 
        /*
        if(referer == 'null' || referer.indexOf('mgoon') > -1 ){
			if(cmtCnt > 0){
        	    $("#replyTab").click();
        	}else{
        		$("#detailInfoTab").click();
        	 }
        }else if(referer.indexOf('twitter') > 0){  // 트위터 유입인 경우 트위터탭 활성화 
       		 $("#twitterTab").click();
        }else{ // 그외 외부 유입인 경우 관련 영상탭 활성화 
	    	$('.side_content').load('/viewutil/tabDetailVideo.htm?id='+vid); 
	    }
	    */
	    if(location.hash == '#cmt'){
			$("#replyTab").click();
		}else{
	   	    $("#relationTab").click();    
	    }
	    // Ajax 호출 시 로딩 바...
        $(document).ajaxStart(function(){
        	$('#loading').show();
        	//$('#loading').html('<img alt="loading" src="/css/lytebox/images/loading.gif" />');
		});
		 $(document).ajaxStop(function(){
        	$('#loading').hide();
		});
		
	//상단 알림 영역 
	c_eventList_time();
	 $("#event_rolling >li >a").hover(
		  function () {
		   clearTimeout(timer); 
		  },
		  function () {
		  	timer = setTimeout( "c_eventList_time()", 3000);
		  }
		);
	BitlyCB.viewShortResponse = function(data) {
		short_url = shortUrlResult(data);
		document.getElementById('linkCopy').value = short_url; 
	};
});

function change_eventList(num)
{
	for(var i=1; i<=$('#event_rolling > li').size(); i++){$('#eventList_'+i).hide();};
	$('#eventList_'+num).show("slow");
}
var ce_num = 0;
var timer ; 
function c_eventList_time(){
	if ( ce_num == $('#event_rolling > li').size() ) ce_num = 1;
	else ce_num = ce_num + 1;
	change_eventList(ce_num);
	timer = setTimeout( "c_eventList_time("+ce_num+")", 10000);
}



function resize() {	
	var bodyheight = $(".container").height();
	var yankHeight = 902 +100; 
	if(bodyheight < yankHeight)
	 $(".container").height(yankHeight);
	
}

/*******************************************************
      영상 사이즈 비율로 플레어어 사이즈 조절 
/*******************************************************/
var pwidth = 590;
var pheight = 0;
function resizePlayer(vwidth, vheight){
	var maxHeight = screen.height - 300;
	var minHeight = 365; // 
	pheight = Math.floor(pwidth * vheight / vwidth); 
	if(pheight > maxHeight){ // 플레이어 Height이  정해놓은 최대 Height 보다 클때는 최대 Height로 설정 
		pheight = maxHeight;
	}
    if(pheight > vheight ){ // 플레이어 Height이  원본  Height 보다 클때는 플레이어 Height를 원본 사이즈로 설정 
		pheight = vheight; 
	}
    if(pheight < minHeight){// 플레이어 Height이  정해놓은 최소 Height 보다 작을 때는 최대 Height로 설정 
		pheight = minHeight; 
	}
	$(".main_section").height(pheight);
}
/*******************************************************
       비디오 URL 줄이기 
/*******************************************************/
var short_url="";
function shortUrlResult(data){
	var s = ''; var first_result;
	// Results are keyed by longUrl, so we need to grab the first one.
	for(var r in data.results) {
		first_result = data.results[r]; break;
	}
	short_url = first_result['shortUrl'].toString();
	return short_url;
}
function shortUrl(url){
		if(short_url!="") document.getElementById('linkCopy').value = short_url;
		else BitlyClient.shorten(url, 'BitlyCB.viewShortResponse');
}
//로그인 완료 한 경우 
function LoginComplete(){
	$.ajaxSetup({cache:false}); 
	$("#site_cover").load('/common/gnb.jsp', function(){
		$.post("/viewutil/getRelationShip.htm",{owner : vowner, stationId: stationId}, function(data){
				if(Boolean(data.isMyVideo)){	
					$(".container").attr("id", "green");
					$("#sendFollowing").hide();
					$("#sendFriend").hide();
				}else if(Boolean(data.hasRelationship)){
					$(".container").attr("id", "pink");
					$("#sendFriend").hide();
				}
				if(Boolean(data.hasFollowing)){
					$("#sendFollowing").hide();
				}
				userNo = data.userNo;
				if($("#replyTab").hasClass("on")){
					cmtReload();
				}
			}, "json");
			loginInfoBox();
	});
}
/***************************************************************
	중앙 메뉴 탭 : (상세정보 / 댓글 / 관련동영상 / 엠군@트윗 탭) 클릭시 이벤트 처리 
*************************************************************/
//상세정보 탭 
$("#detailInfoTab").live('click',function(){
	allLayerClose();
    $('.category_tab > li > a').removeClass();
	$(this).addClass("on");
	 $.ajaxSetup({cache:false}); 
	$('.side_content').load('/viewutil/tabDetailVideo.htm?id='+vid, function(){
		$('.side_content').removeClass().addClass('side_content detail');
	});		
});
//댓글 탭
$("#replyTab").live('click',function(){
		allLayerClose();
		$('.category_tab > li > a').removeClass();
	    $(this).addClass("on");
	     $.ajaxSetup({cache:false}); 
		$('.side_content').load('/videocomment/list.htm?vid='+vid+'&ver=1', function(){
			$('.side_content').removeClass().addClass('side_content reply');
			if(userNo){
				document.commentForm.comment.select();
			}
		});
});
//트위터 탭
$("#twitterTab").live('click',function(){
	allLayerClose();
	$('.category_tab > li > a').removeClass();
	$(this).addClass("on");
	$.ajaxSetup({cache:false}); 
	$('.side_content').load('/jsp/view/tab/twitter.jsp', function(){
		$('.side_content').removeClass().addClass('side_content twitter');
	});
});
//관련동영상 탭 
$("#relationTab").live('click',function(){
		allLayerClose();
		$('.category_tab > li > a').removeClass();
	    $(this).addClass("on");
	     $.ajaxSetup({cache:false}); 
		$('.side_content').load('/search/searchVideoByTitle.htm',
			{vid: vid, title: title, c: cid, size:12, dataType : 'vpage'}, function(){
			$(this).removeClass().addClass('side_content related');
			//changeLoginUsrImg();
		});
});

/***************************************************************
	뷰페이지 우측 프로필 영역 "구독 / 친구 신청 " 클릭 이벤트 처리  
*************************************************************/
$("#sendFriend").live('click',function(){
	if(userNo){
		$.post("/mymgoon/sendFriend.htm",{friend:vowner}, function(data){
			alert(data.resultMsg);
		},"json");
	}else{
		goLoginPopup();
    	return;
	}
});

$("#sendFollowing").live('click',function(){
	if(userNo){
		
		$.post("/mymgoon/following.htm",{stationId :stationId}, function(data){
			alert(data.resultMsg);
			$("#sendFollowing").hide();
			$(".feed_follow fieldset").prepend('<q class="off subscribe" title="구독중 입니다.">구독중</q>');
		},"json");
	}else{
		goLoginPopup();
    	return;
	}
});
/***************************************************************
	뷰페이지 우측 프로필 영역 "댓글 / 담아가기 / 좋아해요" 클릭 이벤트 처리  
*************************************************************/
//댓글 버튼 클릭 
$(".video_info .reply").live('click',function(){
	if($('#replyTab').hasClass("on")){
		if(userNo){
			document.commentForm.comment.select();
		}
	}else{
		$('.category_tab li a').removeClass();
	    $('#replyTab').addClass("on");
	    $.ajaxSetup({cache:false}); 
		$('.side_content').load('/videocomment/list.htm?vid='+vid+'&ver=1', function(){
			$('.side_content').removeClass().addClass('side_content reply');
			if(userNo){
				document.commentForm.comment.select();
			}
		});
	}
	location.href="#cmt";
});

//좋아요 버튼 클릭 
$(".video_info .good a").live('click',function(){
	recommend();
});
var _recommend = false;
function recommend(){
    if(!userNo){
    	goLoginPopup();
    	return;
    }
	if(userNo && !_recommend){
	   $.ajaxSetup({cache:false}); 
		$.post("/viewutil/recommendJSON.htm",{id:vid}, function(data){
			alert(data.resultMsg);
			if(data.result==1){
					//$("li.good span.num")[0].innerHTML
					// = parseInt($("li.good span.num")[0].innerHTML)+1 + " 명";
					$("li.good span.num").html(parseInt($("li.good span.num").html())+1 + " 명");
				}
		},"json");
	}
}
//담아가기 버튼 클릭
$('.video_info .feed a').live('click',function(){
	allLayerClose();
	openScrapLayer();
});
//폰전송 버튼 클릭 
$('#btnPhone').live('click',function(){
	allLayerClose();
	openPhoneLayer();
});
//동영성퍼가기 버튼 클릭 
$('#btnYank').live('click',function(){
	allLayerClose();
	openYankLayer();
});

/**
	댓글 탭 영역 리로드 
**/
function cmtReload(){
	 $.ajaxSetup({cache:false}); 
	$('.side_content').load('/videocomment/list.htm?vid='+vid+'&ver=1', function(){
		if(userNo){
			document.commentForm.comment.select();
		}
	});
}
/*********************************************************
	레이어 (담아가기 , 폰전송, 동영상 퍼가기 )
***********************************************************/
function allLayerClose(){
	$('.layer_popup').hide();
	$('.container').css({'height' : 'auto'});
}
// 담아가기 레이어 오픈 
function openScrapLayer(){
    if(!userNo){
    	goLoginPopup();
    	return;
    }
	 if(userNo==vowner){
	    	alert("본인의 영상입니다.");
	 }else{
	 	 $.ajaxSetup({cache:false}); 
	    $.post('/viewutil/jsonIsScrap.htm?id='+vid,function(data){
	    	if(Boolean(data.result)){
	    		alert('이미 담아가신 영상입니다.');
	    	}else{
	    		 $.ajaxSetup({cache:false}); 
	    		$('#feed_layer').load('/viewutil/layerScrap.htm?id='+vid, function(){
			 		$(this).show();
			 	});
	    	}
	    }, 'json');
	 	
	 }
}
//담아가기 레이어 닫기 
function closeScrapLayer(){
	document.getElementById('feed_layer').style.display = 'none';
	
}
 //폰전송 레이어 오픈 
function openPhoneLayer(){
	 $.ajaxSetup({cache:false}); 
	$('#mobile_layer').load('/jsp/view/layer/sendPhone.jsp', {vid : vid, title : title},function(){
		$(this).show();
		});
}
 //동영상 퍼가기  레이어 오픈 
function openYankLayer(){
	resize();
	 $.ajaxSetup({cache:false}); 
	//$('#scrap').load('/jsp/view/layer/yank.jsp', {vid : vid, title : title},function(){
	//	$(this).show();
	//	});
	$('#ifrmYank').attr("src", "/jsp/view/layer/yank.jsp?vid="+vid);
	$("#scrap").height(840);
	$('#scrap').show();
}

	$('#scrap_layer_close').live('click',function(){
		$('#ifrmYank').attr("src","");
		$('#scrap').hide();
		$('.container').css({'height' : 'auto'});
		
	});
/*********************************************************
	하단 광고 영역 
***********************************************************/
function resizeFrame_view2(frmName, height){
	var frm = document.getElementById(frmName);
	frm.style.height = "auto";
	contentHeight = frm.contentWindow.document.documentElement.scrollHeight;
	frm.style.height = Number(contentHeight + height) + "px";
}
//신고하기 
function accuse(videoId){
	window.open ('/viewutil/accuse.htm?id='+videoId, "","status=0,toolbar=0,resize=0, width=430, height=420");
}

/*******************************************************
	플레이어 용 자바스크립트 영역
********************************************************/
function FlashPlayer_Chk(VID, w, h, playType,viralType){
	 var strView = '<object id="V' + VID + '" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+w+'" height="'+h+'" align="middle"> ' +
	  '<param name="allowScriptAccess" value="always" /> ' +
	  '<param name="allowFullScreen" value="true" /> ' +
	  '<param name="movie" value="http://play.mgoon.com/'+playType+'/V'+ VID + '/" /> ' +
	  '<param name="FlashVars" value="viral='+viralType+'">'+
	  '<param name="quality" value="high" /> ' +
	  '<param name="wmode" value="transparent" />' +
	  '<embed src="http://play.mgoon.com/'+playType+'/V'+ VID +'/"  FlashVars="viral='+viralType+'" wmode="transparent" quality="high" width="'+w+'" height="'+h+'" allowFullScreen="true" name="V' + VID + '"  id="V' + VID + '"  align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>';
	 document.write(strView);
	}
// 플레이어 와이드 호출 스크립트 
function mgoonPlayerExpand(type, width, height){
	if(type){
		$('.view_page_main').css({'top':0,'left':0,'width': width,'height':height, 'z-index': 300 });
		$('.player').css('z-index', 400);
		$('.bg_top').hide();
		$('.bg_bottom').hide();
		$(".main_section").height(360);
	}else{

		$('.view_page_main').css({'top':0,'left':0,'width':pwidth,'height':pheight });
		$('.player').css('z-index', 0);
		$('.bg_top').show();
		$('.bg_bottom').show();
		$(".main_section").height(pheight);
	}
	return true;
}
//플레이어 일시 정지/플레이 할 경우 플레이어 위 플로팅 광고 
function  floatingAdvert(type, flag){
	
	$('.player_ad').hide();
	if(flag){
		$('#player_ad').attr("src", "/jsp/view/layer/floatingAd.jsp");
		 setTimeout("$('.player_ad').show()",1000);
		//$('.player_ad').show();
	}else{
		$('#player_ad').attr("src", "");
	}
}

