﻿
function checkCreateChannel(frm){
	if (frm.cateID.value == 0){
		nhAlertRed("Bạn chưa chọn chủ đề của kênh muốn tạo");
		frm.cateID.focus();
		return false;
	}else if (frm.channelName.value.length <= 1){
		nhAlertRed("Bạn chưa nhập tên kênh");
		frm.channelName.focus();
		return false;
	}else if ((frm.langVN.checked == false) && (frm.langEN.checked == false)) {
		nhAlertRed("Bạn chưa chọn ngôn ngữ phù hợp với kênh");
		return false;
	}else{
		return true;
	}	
}

function checkRegister(frm){
	if (frm.fullName.value.length <= 1){
		nhAlertRed("Bạn chưa nhập tên");
		frm.fullName.focus();
		return false;
	}else if (frm.userID.value.length <= 1){
		nhAlertRed("Bạn chưa nhập tên đăng nhập");
		frm.userID.focus();
		return false;
	}else if (frm.password.value.length <= 1){
		nhAlertRed("Bạn chưa nhập mật khẩu");
		frm.password.focus();
		return false;
	}else if (frm.password.value != frm.password2.value){
		nhAlertRed("Nhập lại mật khẩu không chính xác");
		frm.password2.focus();
		return false;
	}else if (frm.email.value.length <= 1){
		nhAlertRed("Bạn chưa nhập địa chỉ email");
		frm.email.focus();
		return false;
	}else if (frm.birthYear.value == 0){
		nhAlertRed("Bạn chưa chọn năm sinh");
		frm.birthYear.focus();
		return false;
	}else if (frm.agree.checked == false) {
		nhAlertRed("Bạn chưa chọn đồng ý với các điều khoản sử dụng của website");
		frm.agree.focus();
		return false;
	}else{
		return true;
	}	
}

function checkLogin(frm){
	if (frm.userID.value.length <= 1){
		nhAlertRed("Bạn chưa nhập tên đăng nhập");
		frm.userID.focus();
		return false;
	}else if (frm.password.value.length <= 1){
		nhAlertRed("Bạn chưa nhập mật khẩu");
		frm.password.focus();
		return false;
	}else{
		return true;
	}	
}

function sendComment(lang, frm){
	if (frm.comment.value.length <= 1){
		nhAlertRed("Bạn chưa nhập bình luận");
		frm.comment.focus();
		return false;
	}else{
		var contentArray = new Array();	
		contentArray['clipID'] = frm.clipID.value;
		contentArray['comment'] = frm.comment.value;
		nhAjax("/" + lang + "/send_clipcomment/", contentArray);		
		return true;
	}	
}

function turnChannelList_4AddClip(){
	if (_('channellist_4addclip').style.display == "none"){
		_('channellist_4addclip').style.display = "";
	}else{
		_('channellist_4addclip').style.display = "none";
	}
}
	
function changeChannel4AddClip(lang, thisSelect){
	var cateID = thisSelect.options[thisSelect.selectedIndex].value;
	nhAjax("/" + lang + "/channel4addclip/" + cateID + "/" + 1);	
	return false;	
}

function searchYoutube(lang, frm){
	keyword = frm.keyword.value;
	window.location.href="/" + lang + "/ysearch/2/1/" + keyword;
	return false;
}

function selectAllSearchedClip(frm, thisCheckbox){
	var newState = thisCheckbox.checked;
    var elts      = frm.elements["clipID[]"];
    var elts_cnt  = (typeof(elts.length) != 'undefined')? elts.length: 0;
    if (elts_cnt) {
        for (var i = 0; i < elts_cnt; i++) {
            elts[i].checked = newState;
        }
    }	
}

function addClip2Channel(lang, frm){
	clipIDList = getCheckedInput(frm, "clipID[]");
	channelIDList = getCheckedInput(getObj('channelList4AddClip_Form'), "channelID[]");
			
	//alert(clipIDList + " - " + channelIDList);
	
	var contentArray = new Array();	
	if (clipIDList == ""){
		nhAlertRed("Bạn chưa chọn clip nào");
		return false;
	}else if (channelIDList == ""){
		nhAlertRed("Bạn chưa chọn kênh để đưa clip vào");
		return false;
	}
	
	contentArray['clipIDList'] = clipIDList;
	contentArray['channelIDList'] = channelIDList;
	nhAjax("/" + lang + "/addcliplist_2channel/", contentArray);	
	turnChannelList_4AddClip();
}

function getCheckedInput(frm, inputName){
    var elts      = frm.elements[inputName];
    var elts_cnt  = (typeof(elts.length) != 'undefined')? elts.length: 0;    
	var websiteList = "";
    if (elts_cnt) {
        for (var i = 0; i < elts_cnt; i++) {
            if (elts[i].checked == true){            	            	            	
            	websiteList += elts[i].value + ",";
            }
        }
    }else if (frm.elements[inputName].checked) {
		websiteList = frm.elements[inputName].value;
    }
    return websiteList;
}





function nhConfirmRed(msg, confirmAction){
var htmlLayer = "";
	htmlLayer += '<table style="border:#c7434a 1px solid; background:#f8ffab; padding:2px;" width="428" height="140" border="0" cellspacing="0" cellpadding="0">';
	htmlLayer += '<tr><td align="center" valign="middle"><table width="422" height="149" border="0" cellspacing="0" cellpadding="0">';
	htmlLayer += '  <tr><td height="22" background="/images/red_head_thongbao.jpg" class="text11_white" align="left" valign="middle">&nbsp;&nbsp;&nbsp;&nbsp;<strong>Cần xác nhận</strong></td>';
	htmlLayer += '  <td background="/images/red_head_thongbao.jpg" valign="middle" align="right"><img src="/images/red_close_thongbao.jpg" border="0" onclick="dialog2.hide(); return false;" style="cursor:pointer"/>&nbsp;</td></tr>';
	htmlLayer += '  <tr><td height="62" colspan="2" align="left" valign="top" class="text11_black" style="padding:18px 13px 0px 13px;">' + msg + '</td></tr>';
	htmlLayer += '  <tr><td height="40" colspan="2" align="right" valign="top" style="padding:0px 16px;">';
	htmlLayer += '  <input type="button" value=" Không " class="bottom_button" style="background:url(/images/bg_big_button_white.jpg)" onclick="dialog2.hide(); return false;" style="cursor:pointer" />';
	htmlLayer += '  <input type="button" value=" Có " class="bottom_button" style="background:url(/images/bg_big_button_blue.jpg)" onclick="dialog2.hide(); eval(' + confirmAction + '); return false;" style="cursor:pointer" /> ';		  
	htmlLayer += '  </td></tr>';
	htmlLayer += '</table></td></tr></table>';		
	
	showAlert(htmlLayer);
}

function nhConfirmBlue(msg, confirmAction){
var htmlLayer = "";
	htmlLayer += '<table style="border:#4c709b 1px solid; background:#e6ecf1; padding:2px;" width="428" height="140" border="0" cellspacing="0" cellpadding="0">';
	htmlLayer += '<tr><td align="center" valign="middle"><table width="422" height="149" border="0" cellspacing="0" cellpadding="0">';
	htmlLayer += '<tr><td height="22" background="/images/blue_head_thongbao.jpg" class="text11_white" align="left" valign="middle">&nbsp;&nbsp;&nbsp;&nbsp;<strong>Cần xác nhận</strong></td>';
	htmlLayer += '<td background="/images/blue_head_thongbao.jpg" valign="middle" align="right"><img src="/images/blue_close_thongbao.jpg" border="0" onclick="dialog2.hide(); return false;" style="cursor:pointer" />&nbsp;</td></tr>';
	htmlLayer += '<tr><td height="62" colspan="2" align="left" valign="top" class="text11_black" style="padding:18px 13px 0px 13px;">' + msg + '</td></tr>';
	htmlLayer += '<tr><td height="40" colspan="2" align="right" valign="top" style="padding:0px 16px;">';
	htmlLayer += ' <input type="button" value=" Không " class="bottom_button" style="background:url(/images/bg_big_button_white.jpg)" onclick="dialog2.hide(); return false;" style="cursor:pointer" />';
	htmlLayer += ' <input type="button" value=" Có " class="bottom_button" style="background:url(/images/bg_big_button_blue.jpg)" onclick="dialog2.hide(); eval(' + confirmAction + '); return false;" style="cursor:pointer" />';				 		 
	htmlLayer += '</td></tr>';
	htmlLayer += '</table></td></tr></table>';
	
	showAlert(htmlLayer);
}


function nhAlertRed(msg){
var htmlLayer = "";
	htmlLayer += '<table style="border:#c7434a 1px solid; background:#f8ffab; padding:2px;" width="428" height="140" border="0" cellspacing="0" cellpadding="0">';
	htmlLayer += '<tr><td align="center" valign="middle"><table width="422" height="149" border="0" cellspacing="0" cellpadding="0">';
	htmlLayer += '  <tr><td height="22" background="/images/red_head_thongbao.jpg" class="text11_white" align="left" valign="middle">&nbsp;&nbsp;&nbsp;&nbsp;<strong>Thông báo</strong></td>';
	htmlLayer += '  <td background="/images/red_head_thongbao.jpg" valign="middle" align="right"><img src="/images/red_close_thongbao.jpg" border="0" onclick="dialog2.hide(); return false;" style="cursor:pointer"/>&nbsp;</td></tr>';
	htmlLayer += '  <tr><td height="62" colspan="2" align="left" valign="top" class="text11_black" style="padding:18px 13px 0px 13px;">' + msg + '</td></tr>';
	htmlLayer += '  <tr><td height="40" colspan="2" align="right" valign="top" style="padding:0px 16px;">';
	htmlLayer += '  <input type="button" value=" OK " class="bottom_button" style="background:url(/images/bg_big_button_white.jpg)" onclick="dialog2.hide(); return false;" style="cursor:pointer" />';
	htmlLayer += '  </td></tr>';
	htmlLayer += '</table></td></tr></table>';		
	
	showAlert(htmlLayer);
}

function nhAlertBlue(msg){
var htmlLayer = "";
	htmlLayer += '<table style="border:#4c709b 1px solid; background:#e6ecf1; padding:2px;" width="428" height="140" border="0" cellspacing="0" cellpadding="0">';
	htmlLayer += '<tr><td align="center" valign="middle"><table width="422" height="149" border="0" cellspacing="0" cellpadding="0">';
	htmlLayer += '<tr><td height="22" background="/images/blue_head_thongbao.jpg" class="text11_white" align="left" valign="middle">&nbsp;&nbsp;&nbsp;&nbsp;<strong>Thông báo</strong></td>';
	htmlLayer += '<td background="/images/blue_head_thongbao.jpg" valign="middle" align="right"><img src="/images/blue_close_thongbao.jpg" border="0" onclick="dialog2.hide(); return false;" style="cursor:pointer" />&nbsp;</td></tr>';
	htmlLayer += '<tr><td height="62" colspan="2" align="left" valign="top" class="text11_black" style="padding:18px 13px 0px 13px;">' + msg + '</td></tr>';
	htmlLayer += '<tr><td height="40" colspan="2" align="right" valign="top" style="padding:0px 16px;">';
	htmlLayer += ' <input type="button" value=" OK " class="bottom_button" style="background:url(/images/bg_big_button_white.jpg)" onclick="dialog2.hide(); return false;" style="cursor:pointer" />';
	htmlLayer += '</td></tr>';
	htmlLayer += '</table></td></tr></table>';
	
	showAlert(htmlLayer);
}






//AUTO PLAY

function changeCookiePlay(eventObject){
	$.cookie("playItem["+$(this).attr('c9_id')+"][play]", this.checked, { expires: 365, path: '/' });

	var clip_chkboxs = $("#clips_by_channel :checkbox");
	var totalDuration = 0;	
	for(var i=0; i<clip_chkboxs.length; i++){
		if(clip_chkboxs[i].checked == true){	
			totalDuration += parseInt($(clip_chkboxs[i]).attr("yt_duration"));		
		}
	}
	$("#totalPlayTime").html(Math.round(totalDuration/60) + " min");		
}

saveCookieData = function(){};
checkClipSameChannel = function(){};

function deleteCookiesByPattern(pattern){
	var arrCookies = document.cookie.split("; ");
	var cookieComponents;
	var re = new RegExp(pattern);
	for(var i = 0; i < arrCookies.length; i++){
		cookieComponents = arrCookies[i].split("=");
		if(cookieComponents[0].match(re)){
			$.cookie(cookieComponents[0], null);
		}
	}
}

function checkAllClipsByChannel(value){
	var clip_chkboxs = $("#clips_by_channel :checkbox");
	for(var i=0; i<clip_chkboxs.length; i++){
		clip_chkboxs[i].checked = value;
	}
	saveCookieData();
}

saveCookieData = function(){
	deleteCookiesByPattern(/playItem\[.+?\]\[.+?\]/);
	var clip_chkboxs = $("#clips_by_channel :checkbox");
	var clip_names = $("#clips_by_channel a.clipName");	
	if(clip_chkboxs.length==clip_names.length){
		var c9ID;
		for(var i=0; i<clip_chkboxs.length; i++){
			c9ID = $(clip_chkboxs[i]).attr("c9_id");			
			$.cookie("playItem["+c9ID+"][play]", clip_chkboxs[i].checked, { expires: 365, path: '/'});
			$(clip_chkboxs[i]).click(changeCookiePlay);
			//alert("SET: " + c9ID + " = " + clip_chkboxs[i].checked);			
		}
	}
};

function getPlayingID(){
	var re = new RegExp(/\/\d+?\/\d+?\/\d+?\/(\d+?)\/.*$/);
	var m = re.exec(window.location.href);
	if(m == null){
		return null;
	}
	else{
		return m[1];
	}
}

function onPlayerStateChange(newState) {
	//alert("State change state = " + newState);
	if(newState == 0){
		//if($("#nextClip a:first").attr("href")) $("#nextClip a:first").click();//
		if ($.cookie("autoState") == "1"){
			if($("#nextClip a:first").attr("href")) window.location.href=$("#nextClip a:first").attr("href");
		}
	}
}

function onYouTubePlayerReady(playerId) {	
	ytplayer = document.getElementById("myytplayer");
	setInterval(updateytplayerInfo, 500);
	ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
	//ytplayer.addEventListener("onError", "onytplayerError");
}

function updateytplayerInfo() {
	if ($.cookie("autoState") == "1"){
		$("#inTime").html("AUTO: <b>" + Math.round(getDuration() - getCurrentTime()) + "</b> sec &nbsp <a href='javascript:void(0);' class='clipName txt12' onClick='changeAutoState();'>stop</a>");
	}else{
		$("#inTime").html("<a href='javascript:void(0);' class='clipName txt12' onClick='changeAutoState();'>RESTART AUTOPLAY</a>");	
	}
}

function changeAutoState(){
	if ($.cookie("autoState") == "0"){
		$.cookie("autoState", "1", { expires: 0.1, path: '/' });
	}else{
		$.cookie("autoState", "0", { expires: 0.1, path: '/' });
	}
}

function onytplayerError(errorCode) {
	if($("#nextClip a:first").attr("href"))
		if(confirm("Clip bạn đang xem bị lỗi, trình duyệt sẽ tự động chuyển đến bài tiếp theo..."))
			 $("#nextClip a:first").click();//window.location.href=$("#nextClip a:first").attr("href");
}

checkClipSameChannel = function(){
	var clip_chkboxs = $("#clips_by_channel :checkbox[c9_id]"); //clipSameChannel clips_by_channel
	var playingID = getPlayingID();
	var c9ID;
	var firstClipID = "";
	var getFirstClipID = true;
	var secondClipID = "";
	var getSecondClipID = false;
	var nextClipID = "";
	var getNextClipID = false;
	var totalDuration = 0;
	
	for(var i=0; i<clip_chkboxs.length; i++){
		c9ID = $(clip_chkboxs[i]).attr("c9_id");		
		//alert("GET " + c9ID + " = " + $.cookie("playItem["+c9ID+"][play]"));
		if($.cookie("playItem["+c9ID+"][play]")=="true"){	
			totalDuration += parseInt($(clip_chkboxs[i]).attr("yt_duration"));		
			clip_chkboxs[i].checked = true;
			if(getFirstClipID && playingID!=c9ID){
				firstClipID = c9ID;
				getFirstClipID = false;
				getSecondClipID = true;
			}
			if(getSecondClipID){
				secondClipID = c9ID;
				getSecondClipID = false;
			}
			if(playingID==c9ID){
				clip_chkboxs[i].checked = false;
				getNextClipID = true;
			}
			else if(getNextClipID){
				nextClipID = c9ID;
				getNextClipID = false;
			}
		}
		else{
			clip_chkboxs[i].checked = false;
		}
		$(clip_chkboxs[i]).click(changeCookiePlay);
	}
	$("#totalPlayTime").html(Math.round(totalDuration/60) + " min");		
	
	if(nextClipID == ""){
		if(firstClipID == playingID){
			nextClipID = firstClipID;
		}
		else{
			nextClipID = secondClipID;
		}
	}
	if(nextClipID!=""){
		$("#nextClip").html("Clip tiếp: <a href=\""+$("#playUrl_"+nextClipID).attr("href")+"\" class=\"clipName txt12\" title=\""+$("#playUrl_"+nextClipID).text()+"\">"+$("#playUrl_"+nextClipID).text()+"</a>");
	}

	//play clip
	if(!playingID){
		playingID = firstClipID;
	}
	$.cookie("playItem["+playingID+"][play]", false, { expires: 365, path: '/'});
}


// functions for the api calls
function loadNewVideo(id, startSeconds) {
  if (ytplayer) {
    ytplayer.loadVideoById(id, parseInt(startSeconds));
  }
}

function cueNewVideo(id, startSeconds) {
  if (ytplayer) {
    ytplayer.cueVideoById(id, startSeconds);
  }
}

function play() {
  if (ytplayer) {
    ytplayer.playVideo();
  }
}

function pause() {
  if (ytplayer) {
    ytplayer.pauseVideo();
  }
}

function stop() {
  if (ytplayer) {
    ytplayer.stopVideo();
  }
}

function getPlayerState() {
  if (ytplayer) {
    return ytplayer.getPlayerState();
  }
}

function seekTo(seconds) {
  if (ytplayer) {
    ytplayer.seekTo(seconds, true);
  }
}

function getBytesLoaded() {
  if (ytplayer) {
    return ytplayer.getVideoBytesLoaded();
  }
}

function getBytesTotal() {
  if (ytplayer) {
    return ytplayer.getVideoBytesTotal();
  }
}

function getCurrentTime() {
  if (ytplayer) {
    return ytplayer.getCurrentTime();
  }
}

function getDuration() {
  if (ytplayer) {
    return ytplayer.getDuration();
  }
}

function getStartBytes() {
  if (ytplayer) {
    return ytplayer.getVideoStartBytes();
  }
}

function mute() {
  if (ytplayer) {
    ytplayer.mute();
  }
}

function unMute() {
  if (ytplayer) {
    ytplayer.unMute();
  }
}

function getEmbedCode() {
  alert(ytplayer.getVideoEmbedCode());
}

function getVideoUrl() {
  alert(ytplayer.getVideoUrl());
}

function setVolume(newVolume) {
  if (ytplayer) {
    ytplayer.setVolume(newVolume);
  }
}

function getVolume() {
  if (ytplayer) {
    return ytplayer.getVolume();
  }
}

function clearVideo() {
  if (ytplayer) {
    ytplayer.clearVideo();
  }
}
