/*======================================================================*\
|| #################################################################### ||
|| # AT Movie 1.0                                                     # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright © 2008-2009 AnhTrang.Org . All Rights Reserved.         # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ----------- AT MOVIE IS FREE SOFTWARE - OPEN SOURCE ------------ # ||
|| # http://www.anhtrang.org | http://www.anhtrang.org/support.html   # ||
|| #################################################################### ||
\*======================================================================*/

var http = createRequestObject();
var field = '';
var i=0;
var MainLoading = "<div id='load' class='img'><img src='"+web_link+"/images/loading.gif'></div>";
var pl_loading = "<span class='img'><img src='"+web_link+"/images/pl_loading.gif'></span>";
var RATE_OBJECT_IMG = ""+web_link+"/images/rate/full.gif";
var RATE_OBJECT_IMG_HOVER = ""+web_link+"/images/rate/full.gif";
var RATE_OBJECT_IMG_HALF = ""+web_link+"/images/rate/half.gif";
var RATE_OBJECT_IMG_BG = ""+web_link+"/images/rate/none.gif";
		   
function showResult(id,data) {
	exitContent('loading');
	$("#"+id).html(data);
}

function showLoader() {
	$("#loading").show();
	$("#loading").html(MainLoading);
}

function exitContent(id) {
	$('#'+id).html('').hide();
}		   
		   
function createRequestObject() {
	var xmlhttp;
	try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); }
	catch(e) {
    try { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
	catch(f) { xmlhttp=null; }
  }
  if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
	xmlhttp=new XMLHttpRequest();
  }
	return  xmlhttp;
}

function trim(a) {
	return a.replace(/^s*(S*(s+S+)*)s*$/, "$1");
}

function handleResponse() {
	try {
		if((http.readyState == 4)&&(http.status == 200)){
			document.getElementById("loading").style.display = "none";
			response = http.responseText;
			field.innerHTML = response;
			field.scrollIntoView();
			if(!response) window.location.href = url;
		}
  	}
	catch(e){}
	finally{}
}

function str_replace(search, replace, str){
	var ra = replace instanceof Array, sa = str instanceof Array, l = (search = [].concat(search)).length, replace = [].concat(replace), i = (str = [].concat(str)).length;
	while(j = 0, i--)
		while(str[i] = str[i].split(search[j]).join(ra ? replace[j] || "" : replace[0]), ++j < l);
	return sa ? str : str[0];
}

// + ------------------- +
// |    SHOW PLAYLIST    |
// + ------------------- +
function showpl(type) {
	if(type == 1) {
		$('#list-playlist').slideDown();
		$('#showpl').slideUp();
		$('#pl_title').html("Playlist - [<a style=\"cursor:pointer;\" onclick=\"showpl(0);\">ẩn list nhạc</a>]");
	}
	if(type == 0) {
		$('#showpl').slideDown();
		$('#pl_title').html("Playlist");
		$('#list-playlist').slideUp();
		$('#showpl').html("<a style=\"cursor:pointer;\" onclick=\"showpl(1);\">Bấm vào đây</a> để <b>hiện</b> playlist của bạn.");
	}
}

// + ------------------- +
// |    SHOW CHAT - AD   |
// + ------------------- +

//function showchatbox()	{
//	showcb = getCookie('chatbox');
//	chatbox(showcb);
//	noad = getCookie('noad');
//	if(noad == 0) document.getElementById('youtube').fadeIn('fast');
//}


function close_ad()	{
	setCookie("noad",1,1);
	$('#youtube').slideUp();
}


function write_comment(type)	{
	if(type==1)	{
		$('#write_comment').slideDown();
		$('#new_comment').slideUp();
	}
	if(type==0)	{
		$('#write_comment').slideUp();
		$('#new_comment').slideDown();
	}	
}

function chatbox(type) {
	if(type == 1) {
		setCookie('chatbox',1,365);
		$('#cboxdiv').show('fast');
		$('#showchat').hide('fast');
		$('#cbox_title').html("Tán ngẫu - [<a style=\"cursor:pointer;\" onClick=\"chatbox(0)\">ẩn khung chat</a>]");
	}
	if(type == 0) {
		setCookie('chatbox',0,365);
		$('#cboxdiv').hide('fast');
		$('#showchat').show('fast');
		$('#cbox_title').html("Tán ngẫu");
		$('#showchat').html("<a style=\"cursor:pointer;\" onclick=\"chatbox(1);\">Bấm vào đây</a> để <b>hiện</b> khung chat.");
	}
}

function lyricbox(type) {
	if(type == 1) {
		$('#lyricdiv').slideDown();
	}
	if(type == 0) {
		$('#lyricdiv').slideUp();
	}
}

function cmtbox(type) {
	if(type == 1) {
		$('#cmtdiv').slideDown();
	}
	if(type == 0) {
		$('#cmtdiv').slideUp();
	}
}

function albumbox(type) {
	if(type == 1) {
		$('#albumdiv').show();
	}
	if(type == 0) {
		$('#albumdiv').hide();
	}
}

function artistbox(type) {
	if(type == 1) {
		$('#artistdiv').show();
	}
	if(type == 0) {
		$('#artistdiv').hide();
	}
}

// + ------------------- +
// |      SEARCH         |
// + ------------------- +
function do_search() {
	tab = $("#t").val();
	kw = $("#keyword").val();
	kw = str_replace(' ', '-', kw);
	kw = str_replace('%20', '-', kw);
	if (!kw) return false;
	else {
		kw = encodeURIComponent(kw);
		window.location.href = web_link+'/tim-kiem/'+kw+'/'+tab+'.html';	
	}
  return false;
}

// + ------------------- +
// |    ADD EMOTICON     |
// + ------------------- +
function addText(elname, wrap1, wrap2) {
	if (document.selection) { // for IE 
		var str = document.selection.createRange().text;
		document.forms['add'].elements[elname].focus();
		var sel = document.selection.createRange();
		sel.text = wrap1 + str + wrap2;
		return;
	} else if ((typeof document.forms['add'].elements[elname].selectionStart) != 'undefined') { // for Mozilla
		var txtarea = document.forms['add'].elements[elname];
		var selLength = txtarea.textLength;
		var selStart = txtarea.selectionStart;
		var selEnd = txtarea.selectionEnd;
		var oldScrollTop = txtarea.scrollTop;
		var s1 = (txtarea.value).substring(0,selStart);
		var s2 = (txtarea.value).substring(selStart, selEnd)
		var s3 = (txtarea.value).substring(selEnd, selLength);
		txtarea.value = s1 + wrap1 + s2 + wrap2 + s3;
		txtarea.selectionStart = s1.length;
		txtarea.selectionEnd = s1.length + s2.length + wrap1.length + wrap2.length;
		txtarea.scrollTop = oldScrollTop;
		txtarea.focus();
		return;
	} else {
		insertText(elname, wrap1 + wrap2);
	}
}

// + ------------------- +
// |     COUNT WORDS     |
// + ------------------- +
var submitcount=0;
   function checkSubmit() {

      if (submitcount == 0)
      {
      submitcount++;
      document.Surv.submit();
      }
   }


function wordCounter(field, countfield, maxlimit) {
wordcounter=0;
for (x=0;x<field.value.length;x++) {
      if (field.value.charAt(x) == " " && field.value.charAt(x-1) != " ")  {wordcounter++}
      if (wordcounter > 250) {field.value = field.value.substring(0, x);}
      else {countfield.value = maxlimit - wordcounter;}
      }
   }

function textCounter(field, countfield, maxlimit) {
  if (field.value.length > maxlimit)
      {field.value = field.value.substring(0, maxlimit);}
      else
      {countfield.value = maxlimit - field.value.length;}
  }
  
// + ------------------- +
// |      NEWS CMT       |
// + ------------------- +
function show_news_comment(num,news_id,page) { 

	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'show_news_comment=1&num='+num+'&news_id='+news_id+'&page='+page,
		dataType: 'html',
		success: function(data) {
			showResult("news_comment_field",data);
			return false;
		}
	});
	return false;
} 

function news_comment_check_values() {

	news_id = $("#news_id").val();
	num = $("#num").val();
	comment_poster = $("#comment_poster").val();
	comment_content = $("#comment_content").val();

	showLoader();
	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'news_comment=1&news_id='+news_id+'&num='+num+'&comment_poster='+comment_poster+'&comment_content='+comment_content,
		dataType: 'html',
		success: function(data) {
			if (data== 'OK') {
				news_id = $("#news_id").val();
				num = $("#num").val();
				show_news_comment(num,news_id,1);
				$('#loading').hide();
			}
			else {
				$('#loading').hide();
				alert(data);
			}
		}
	});	
	return false;
}  
  
  
// + ------------------- +
// |       COMMENT       |
// + ------------------- +
function showComment(num,media_id,page) { 

	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'showcomment=1&num='+num+'&media_id='+media_id+'&page='+page,
		dataType: 'html',
		success: function(data) {
			showResult("comment_field",data);
			return false;
		}
	});
	return false;
} 

function comment_check_values() {

	media_id = encodeURIComponent($("#media_id").val());
	num = encodeURIComponent($("#num").val());
	comment_poster = encodeURIComponent($("#comment_poster").val());
	comment_content = encodeURIComponent($("#comment_content").val());
	
	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'comment=1&media_id='+media_id+'&num='+num+'&comment_poster='+comment_poster+'&comment_content='+comment_content,
		dataType: 'html',
		success: function(data) {
			if (data == 'OK') {
				media_id = encodeURIComponent($("#media_id").val());
				num = encodeURIComponent($("#num").val());
				showComment(num,media_id,1);
			}
			else {
				$("loading").hide();
				alert(data);
			}
		}
	});
	return false;
}

// + ------------------- +
// |      RATING         |
// + ------------------- +
function rating(media_id,star) {

	showLoader();
	hide_rating_process();
	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'rating=1&media_id='+media_id+'&star='+star,
		dataType: 'html',
		success: function(data) {
			showResult("rating_field",data);
			return false;
		}
	});
	return false;
}


	// pre-fetch image
	(new Image()).src = RATE_OBJECT_IMG;
	(new Image()).src = RATE_OBJECT_IMG_HALF;
	(new Image()).src = RATE_OBJECT_IMG_BG;

	function show_star(starNum,rate_text) {
		remove_star();
		document.getElementById("rate_text_d").innerHTML = rate_text;
		full_star(starNum);
	}
	
	function full_star(starNum) {
		for (var i=0; i < starNum; i++)
			document.getElementById('star'+ (i+1)).src = RATE_OBJECT_IMG;
	}
	function remove_star() {
		for (var i=0; i < 5; i++)
			document.getElementById('star' + (i+1)).src = RATE_OBJECT_IMG_BG; // RATE_OBJECT_IMG_REMOVED;
	}
	function remove_all_star() {
		for (var i=0; i < 5; i++) document.getElementById('star' + (i+1)).src = RATE_OBJECT_IMG_BG; // RATE_OBJECT_IMG_REMOVED;
		document.getElementById("rate_text_d").innerHTML = 'Bình Chọn';
	}
	function show_rating_process() {
		if(document.getElementById("rating_process")) document.getElementById("rating_process").style.display = "block";
		if(document.getElementById("rate_s")) document.getElementById("rate_s").style.display = "none";
	}
	function hide_rating_process() {
		document.getElementById("rating_process").style.display = "none";
		if(document.getElementById("rate_s")) document.getElementById("rate_s").style.display = "block";
	}

// + ------------------- +
// |      BROKEN         |
// + ------------------- +
function showBroken(media_id) {
	if(confirm('Bạn có chắc là không nghe được ?')) {}
	else return false;
	
	showLoader();
	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'broken=1&media_id='+media_id,
		dataType: 'html',
		success: function(data) {
			alert(data);
			$('#loading').hide();
		}
	});
	return false;

}
// + ---------------------- +
// | SHOW media
// + ---------------------- +
function showMedia(num,page,number,apr,cat_id) { 
	
	showLoader()
	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'showmedia=1&num='+num+'&page='+page+'&number='+number+'&apr='+apr+'&cat_id='+cat_id,
		dataType: 'html',
		success: function(data) {
			showResult(num,data);
			return false;
		}
	});
	return false; 
	
}

function imposeMaxLength(Object, MaxLen)	{
  return (Object.value.length <= MaxLen);
}

function applyType(obj, value) {
    var arrType = document.getElementsByName('searchType');
    for (var i = 0; i < arrType.length; i++) {
        arrType[i].className = '';
    }
    obj.className = 'curnav';
    document.getElementById("frmsearch").t.value = value;
}
// + ---------------------- +
// |        POPUP           |
// + ---------------------- +
function openWindow(filename, winname, width, height, feature) {
    var features, top, left;
    var reOpera = /opera/i;
    var winnameRequired = ((navigator.appName == "Netscape" && parseInt(navigator.appVersion) == 4) || reOpera.test(navigator.userAgent));

    left = (window.screen.width - width) / 2;
    top = (window.screen.height - height) / 2;
    if (feature == '')
        features = "width=" + width + ",height=" + height + ",top=" + top + ",left=" + left + ",status=0,location=0";
    else
        features = "width=" + width + ",height=" + height + ",top=" + top + ",left=" + left + "," + feature;
    newwindow = window.open(filename, winname, features);
    newwindow.focus();
}
// + ---------------------- +
// |        PLAYLIST        |
// + ---------------------- +

function reloadPlaylist(add_id,remove_id,field) {
	if(add_id == 0) {
		showLoader();
	}
	else {
		if(field == "player") {
			showLoader();
		}
		else $("#pl_loading_"+field).css("background","url("+web_link+"/images/pl_loading.gif)");
	}
	
	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'reloadPlaylist=1&add_id='+add_id+'&remove_id='+remove_id,
		dataType: 'html',
		success: function(data) {
			if(add_id == 0) $("#loading").hide();
			else {
				if(field == "player") {
					$("#loading").hide();
				}	
				else {
					$("#pl_add_"+field).css("background","transparent");
					$("#pl_loading_"+field).css("background","url("+web_link+"/images/tick.png)");
				}
			}
			showResult("playlist_field",data);
			showpl(1);
		}
	});
	return false;
}

function addToPlaylist(song_id,field)
{
	reloadPlaylist(song_id,0,field);
}
function removeFromPlaylist(song_id)
{
	reloadPlaylist(0,song_id);
}
// + ------------------- +
// |        LOGIN        |
// + ------------------- +

function quick_login() {
	name = $("#username").val();
	pwd = $("#password").val();
	if(	name == "" ||	pwd == "" || name == "Tên đăng nhập" || pwd == "xxxxxxxxxxxx" )
		alert("Bạn chưa nhập đầy đủ thông tin");
	else {
	
		showLoader()
		$.ajax({
			url: web_link+'/index.php',
			type: 'POST',
			data: 'login=1&name='+name+'&pwd='+pwd,
			dataType: 'html',
			success: function(data) {
				if(data) {$("#loading").hide(); alert(data); return false; }
				else window.location.reload( false );
			}
		});
	}
	return false; 
}


// + ------------------- +
// |        LOGOUT       |
// + ------------------- +
function logout() {
	if(confirm('Bạn có chắc muốn thoát ?')) {}
	else return false;
	showLoader()
	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'logout=1',
		dataType: 'html',
		success: function(data) {
			$("#loading").hide();
			window.location.reload( false );
		}
	});
	return false; 
}

// + ------------------- +
// |        LANGUAGE     |
// + ------------------- +
function language(lang) {

	showLoader()
	$.ajax({
		url: web_link+'/index.php',
		type: 'POST',
		data: 'language='+lang,
		dataType: 'html',
		success: function(data) {
			$("#loading").hide();
			window.location.reload( false );
		}
	});
	return false; 
}

// + ----------------------------- +
// |        FORGOT PASSWORD        |
// + ----------------------------- +

function forgot() {
	email = $("#u_email").val();
	if(email == "" || email == "Email đã đăng ký")	alert("Bạn chưa nhập email");
	else {
	
		showLoader();
		$.ajax({
			url: web_link+'/index.php',
			type: 'POST',
			data: 'forgot=1&email='+email,
			dataType: 'html',
			success: function(data) {
				$("#loading").hide();
				if (data) {
					$('#forgot_field').hide();
					$('#frmlogin').show();
					alert(data);
				}
			}
		});
	}
	return false; 	
}

// + ----------------------------- +
// |          REGISTER             |
// + ----------------------------- +

function reg_check_values() {

	ok = false;
	name = encodeURIComponent($("#reg_name").val());
	pwd = encodeURIComponent($("#reg_pwd").val());
	pwd2 = encodeURIComponent($("#reg_pwd2").val());
	email = encodeURIComponent($("#reg_email").val());
	sec_num = $("#sec_num").val(); 
	address = $("#address").val();
	agree = document.getElementById("agree").checked;
	
	s = document.getElementsByName("reg_sex");
	if (s[0].checked) sex = s[0].value;
	if (s[1].checked) sex = s[1].value;
	
	if(	trim(name) == "" ||	trim(pwd) == "" ||	trim(pwd2) == "" ||	trim(email) == "" )	{
		$("#response").show();
		$("#response").html("<b><blink>Bạn chưa nhập đầy đủ thông tin</blink></b>");
	}
	else if (pwd != pwd2)	{
		$("#response").show();
		$("#response").html("<b><blink>Xác nhận mật khẩu không chính xác</blink></b>");
	}
	else if (!agree)	{
		$("#response").show();
		$("#response").html("<b><blink>Bạn chưa đồng ý với các quy định của NgheRock.Net</blink></b>");
	}
	else if (sec_num=='')	{
		$("#response").show();		
		$("#response").html("<b><blink>Bạn chưa nhập mã số bảo mật</blink></b>");
	}
	else {
		showLoader();
		$.ajax({
			url: web_link+'/index.php',
			type: 'POST',
			data: 'reg=1&name='+name+'&pwd='+pwd+'&email='+email+'&sex='+sex+'&address='+address+'&sec_num='+sec_num,
			dataType: 'html',
			success: function(data) {
				$("#loading").hide();
				if (data) {
					$("#response").show();
					if(data == "0") {
						$("#response").html("<b><blink>Sai mã bảo mật</blink></b>");
					}
					if(data == "1") {
						$("#response").html("<b><blink>Tài khoản này đã có người sử dụng</blink></b>");
					}
					if(data == "2") {
						$("#response").html("<b><blink>Email không hợp lệ</blink></b>");
					}
					if(data == "3") {
						$("#response").html("<b><blink>Tên sử dụng không hợp lệ. <br>(Tên phải dài từ 3 ký tự trở lên, chỉ gồm chữ cái không dấu và số. Không được có dấu và ký tự đặc biệt)</blink></b>");
					}
					if(data == "4") {
						$("#response").html("<b><blink>Email này đã có người sử dụng</blink></b>");
					}
					document.getElementById('image').src = web_link + '/includes/securimage_show.php?sid=' + Math.random();
				}
				else {
					alert("Chúc mừng bạn đã đăng ký thành công !");
					alert("Bạn có thể đăng nhập ngay bay giờ.");
					window.location.href = web_link;
				}
			}
		});		
	}
	return ok;
}

// + ------------------------- +
// |        CHANGE INFO        |
// + ------------------------- +

function change_info() {
	email = encodeURIComponent($("#u_email").val());
	oldpwd = encodeURIComponent($("#u_oldpwd").val());
	newpwd_1 = encodeURIComponent($("#u_newpwd_1").val());
	newpwd_2 = encodeURIComponent($("#u_newpwd_2").val());
	avatar_input = encodeURIComponent($("#u_avatar_input").val());
    avatar_local = encodeURIComponent($("#u_avatar_local").val()); 
	address = encodeURIComponent($("#address").val()); 
	public_playlist = encodeURIComponent($("#public_playlist").val());
	playlist_name = encodeURIComponent($("#playlist_name").val()); 
	playlist_img = encodeURIComponent($("#playlist_img").val()); 
	playlist_img_old = encodeURIComponent($("#playlist_img_old").val()); 
	s = document.getElementsByName("u_sex");
	if (s[0].checked) sex = s[0].value;
	if (s[1].checked) sex = s[1].value;
	if(	trim(email) == "" )
		alert("Bạn chưa nhập đầy đủ thông tin");
	else if (newpwd_1 != newpwd_2)
		alert("Xác nhận mật khẩu không đúng");
	else {
	
		showLoader()
		$.ajax({
			url: web_link+'/index.php',
			type: 'POST',
			data: 'change_info=1&email='+email+'&address='+address+'&playlist='+public_playlist+'&playlist_name='+playlist_name+'&playlist_img_old='+playlist_img_old+'&playlist_img='+playlist_img+'&oldpwd='+oldpwd+'&newpwd='+newpwd_1+'&sex='+sex+'&avatar_input='+avatar_input+'&avatar_local='+avatar_local,
			dataType: 'html',
			success: function(data) {
				$("#loading").hide();
				if(data) alert(data);
				else window.location.reload( false );
			}
		});
		return false; 	
	}
}


// + ------------------- +
// |      CONTACT        |
// + ------------------- +
function contact() {
	var email = $("#email").val();
	var code = $("#code").val();
	var content = $("#content").val();
	if(!email || !code || !content)	{
		$("#response").show()
		$("#response").html('<blink><b>Bạn chưa nhập đầy đủ thông tin.</b></blink>');
	}

	else {
	
		showLoader();
		document.getElementById("contact_btn").disabled=true;
		document.getElementById("contact_btn").value="Đang gửi tin ...";
		$.ajax({
			url: web_link+'/index.php',
			type: 'POST',
			data: 'contact=1&email='+email+'&code='+code+'&content='+content,
			dataType: 'html',
			success: function(data) {
				$("#loading").hide();
				if (data) {
					$('#forgot_field').hide();
					document.getElementById("contact_btn").disabled=false;
					document.getElementById("contact_btn").value="Gửi đi";
					document.getElementById("response").style.display = "block";
					document.getElementById("response").innerHTML = '<blink><b>'+data+'</b></blink>';
					document.getElementById('siimage').src = web_link + '/includes/securimage_show.php?sid=' + Math.random();
				}
			}
		});
	}
	return false;
}
