/*-------------------------------------------------------------------------
# Pagination ver 1.0 / 25-December-2008
# Author Ken Phan
# Modified:Hoang Van | hoangvan87@gmail.com
# Yahoo Kenphan19
# Email Kenphan19@gmail.com
# Website Kenphan.com
# -------------------------------------------------------------------------
# Company Golden Gate Co.,Ltd
# Websites:  http://www.goldengate.com.vn
# Copyright (C) 2008 GoldenGate Co.,Ltd. All Rights Reserved.
---------------------------------------------------------------------------
# Dual licensed under the MIT and GPL licenses:
# http://www.opensource.org/licenses/mit-license.php
# http://www.gnu.org/licenses/gpl.html
---------------------------------------------------------------------------*/
		
;(function($){
	$.fn.easyPagi = function(options) {
		var defaults = {
			url: "data.php",
			method: "POST",
			busy: "#loading",
			num: 15,
			start: 0,
			query: '',
			type: 0,
			correct: ''
		};
		var opts = jQuery.extend(defaults,options);		
		return this.each(function() {
			$.ajax({
				type: opts.method,
				url: opts.url,
				processData: false,
				dataType: "json",
				beforeSend: function(){
					 $("#loading").css('display','block');					
				},
				success: function(data){
				  $(opts.busy).css('display','none');	
				  beforeResponse(data, opts.url, opts.method, opts.busy, opts.num, opts.start, opts.query, opts.type, opts.correct);
				}
			});
		});
	}
	
	var beforeResponse =  function(data, url, method, busy, num, start, query, type, correct){
		var arrsearch = new Array();
		if( correct == '' )
			correct = query;
		 if( data.rs != "!!!!" ){	
			var scorrect = data.rs;
			arrsearch = scorrect.split("|");
			if(arrsearch[1] != 1)
				correct = arrsearch[0];
			else{
				query = word_limit('singer:' + arrsearch[0]);											    
				correct = query;
				type = 2;				
			}	
		 }			
		$.ajax({
			type: method,
			url: makeUrl(query,num,start,type),
			processData: false,
			dataType: "json",
			beforeSend: function(){
				$(busy).css('display','block');
			},
			success: function (data){
			  $(busy).css('display','none');
				responseJson(data, url, method, busy, num, start, query, type , correct);
			}
		});							
	}
	var responseJson = function(data, url, method, busy, num, start, query, type, correct){
		
		var rowPerPage = num;
		var html = new String();
		var total = parseFloat( data.to > 1000 ? 1000 : data.to );
		var totalPage = Math.floor( total / rowPerPage );
		var current = start/num;
		var record = 5;
		var currentNow = new String();
		var key = $("#key").val();
		var s = new Number();
		var e = new Number();
		var tmp = new Number();
		var ti = new Number();
		s = parseInt(start) + 1;
		//End page
		tmp = parseInt(num) + s - 1;
		if(s == total )
			e = s;
		else if( tmp > total )	
			e = total;
		else
			e = tmp;	
		//Time search
		if(data.ti)
			ti = data.ti;
		else
			ti = 1; 
		//Show result search	
		html = '<div class=total-result>Kết quả <span class=total-numb>' + s + '-' + e + '</span> trong khoảng <span class=total-keyword>';
		html += data.to + '</span> cho <span id=keySearch class=total-word>' + key + '</span> (<span class=total-time>' + parseFloat(ti/100) + '</span> giây)</div>'; 		
		if(data.its != null){		  
		    if(type != 5){		     
            html +='<table><tr><th class=row-1>Tên bài hát / Tác giả</th><th class=row-2>Ca sĩ / Album</th><th class=row-3>Chi tiết</th><th class=row-4>Chức năng</th></tr>';
            $.each(data.its, function( i , item ){              
	              html 							+= '<tr class="row-' + (i%2+1) + '">';
	              if( item.tit) 
	              	html	+= '<td class=row-1>';
	              if( item.tit != null ) 
	              	html 	+= '<a class="title" href="' + base_url + 'mp3/detail/' + item.id + '/' + convert_vn(item.tit) + '.html">' + item.tit + '</a>';
	              if( item.com != null ) 
	              	html	+='<span class=mp3-author>'+item.com + '</span>';
	              html		+= '</td>';
	              html 		+='<td>';
	              if(item.sin != null ) 
	              	html 	+=link_search(item.sin ,'singer%3A' + item.sin ,'mp3',2 ,'',1);//html += item.sin ;
	              if(item.sin !=null) 
	              	html 	+= link_search(item.al,'album%3A' + item.al ,'mp3',4,"mp3-album",1);//item.al;
	              html 		+= '</td>';
	              html 		+='<td>';
	              html 		+='<span class=mp3-kbs>' + item.bit + ' kb/s</span>';
	              var m = Math.floor( item.du/60 );
	              var s = item.du - m*60;
	              if( s < 10 ) s='0' + s;
	              html 		+= '<span class=mp3-time>'+ m + ':' + s + ' / ' + calc_file_size(item.si) + '</span>';
	              html 		+= '</td>';
	              html 		+= '<td class=odd_row>';
	              if(item.ly) {                
	                html 	+= '<div id="id-' + i + '" class="lyric-hidden" rel="' + item.id + '"><b>' + item.tit + '</b></div>';
	                var css   ="mp3-lyric";
	                var href  ='href="javascript:showPopup(\'' + i + '\')";';
	              }else{  
	                var css = "mp3-nolyric";
	                var href = "";
	              }              
	              html		+= '<a href="javascript:return false;" onclick="addEventPlayJust(\'' + item.id + '\',\'' + convert_url(item.url) + '\',\'http://www.socbay.com/mp3.gif\',\'' + item.tit + '\',true);return false;';
	              html		+= '" class="mp3-play"><img title="Nghe nhạc" alt="Nghe nhạc" src="' + base_url + 'public/img/spacer.gif" height=17 width=46 /></a>';
	              html		+=  '<a ' + href +' class="'+css + '"><img alt="Lời bài hát" src="' + base_url + 'public/img/spacer.gif" height=17 width=35 title="Lời bài hát"/></a>';
      			  html		+=  '<a class=mp3-add onclick="addEventPlayJust(\'' + item.id + '\',\'' + convert_url(item.url) + '\',\'http://www.socbay.com/mp3.gif\',\'' + item.tit + '\',false); return false;';
	              html		+= '"><img alt="Thêm vào playlist" src="' + base_url + 'public/img/spacer.gif" height=17 width=46 title="Thêm vào playlist"/></a>';
	              html		+=  '<a href="' +  base_url + 'mp3/download/'+ item.id +'" class="mp3-download"><img alt="Download bài hát" src="' + base_url + 'public/img/spacer.gif" height=17 width=35 title="Lời bài hát"/></a>';            
	              html		+= '</td></tr>';     
	        });
            html			+= '</table>';
		}else{		        
		       
		     html +='<table width=100%>'; 
             html +='<tr>'; 
             html +='<th class=row-lyric>Tên tác giả / Tác giả</th>'; 
             html +='</tr>';              
            $.each(data.its, function( i , item ){       
               if(item.ly)
               { 
                 
                 html +='<tr>'; 
                 html +='<td class=row-lyric>'; 
                 html +='<a href="javascript:openViewLyric(\'' + item.id + '\')" class="title" id="a-' + item.id + '">' + item.tit + '</a>';
                 html +='<div class=lyric-tool>'; 
                 html +='<a class=mp3-play href="javascript: return false;" onclick="addEventPlayJust(\'' + item.id + '\',\'' + convert_url(item.url) + '\',\'http://www.socbay.vn/mp3.gif\',\'' + item.tit + '\',true);return false;" ><img height=17 width=46 src="' + base_url + 'public/img/spacer.gif" alt="Nghe nhạc" title="Nghe nhạc"/></a>';
                 html +='<a class=mp3-add href="javascript: return false;" onclick="addEventPlayJust(\'' + item.id + '\',\'' + convert_url(item.url) + '\',\'http://www.socbay.vn/mp3.gif\',\'' + item.tit + '\',false);return false;" ><img height=17 width=46 src="' + base_url + 'public/img/spacer.gif" alt="Thêm vào playlist" title="Thêm vào playlist"/></a>'; 
                 html +='<a class=mp3-download href="' + base_url + 'mp3/download/' + item.id + '"><img height=17 width=35 src="' + base_url + 'public/img/spacer.gif" alt="Download"/></a>'; 
                 html +='</div>'; 
                 html +='<p class=lyric-info>';
                 if( item.com != "" ) 
                  var com ='Tác giả :' + link_search(item.sin ,item.sin ,'mp3',0 ,'lyric-author',1);
                 else
                  var com ='' ;
                 if( item.sin != "" ) 
                  var sin ='Ca sĩ thể hiện :' + link_search(item.sin ,'singer:' + item.sin ,'mp3',3 ,'lyric-singer',1) ;
                 else
                  var sin = '' ;
                 html += com;
                 html += sin; 
                 html +='</p>'; 
                 html +='<p class=lyric-detail id="lyric_' + item.id + '">' + Base64.decode(item.ly)  + '</p>'; 
                 html +='<p class=lyric-detail id="lyric_click_' + item.id + '" style="display:none">' + Base64.decode(item.ly) + '</p>'; 
                 html +='</td>'; 
                 html +='</tr>'; 
               }
              }); 
              html +='</table>';
		}
        $("#data").html(html);
        $(".mp3-tags-list").show();
    }else{
      $("#data").html('<div class=result><div class=no-result><p>Không tìm thấy <B>' + key + '</B></p><h3>Socbay đề xuất</h3> <ul><li>Xin chắc rằng tất cả các từ khóa đã đúng chính tả .</li> <li>Hãy thử các từ khóa khác .</li> <li>Hãy thử các từ tổng quát hơn .</li> <li>Hay thử bớt từ khóa .</li> </ul><h3>Hướng dẫn và trợ giúp</h3> <ul><li>Xem <a href=http://blog.socbay.com/ target=_blank>hướng dẫn sử dụng các dịch vụ .</a></li> <li>Nếu bạn tìm không thấy trên cơ sở dữ liệu, <a href="http://www.socbay.com/gop_y/" target=_blank>gửi link bạn cần tìm đến cho chúng tôi .</a></li></ul></div></div>');      
      $(".mp3-tags-list").hide();
    }
    
	if(correct != query )
		$("div.total-result").after('<div class="suggestMp3">Có phải bạn muốn tìm: ' + link_search(correct ,word_limit(correct),'mp3',type ,'',1)  + '</div>');		    
	html = '<div id="paging" class="paging">' + Pagination(record,totalPage,current) + '</div>';
	$("#footer").html( html );
	
	//Change page
	$("#pagi li a").click(function(){
		currentNow = $(this).attr("name").substr(4);
		currentNow = parseInt(currentNow) - 1;
		if($(this).attr("name").length > 0)
		{
		  start = parseInt(currentNow)*num;
		  requestPage(start , key);
		  	
		}
	});
	}
	
	var makeUrl = function(query,num,start,type){
	  var url = 'http://www.socbay.com/j_mp3Search_v1/?q='+ query + '&num=' + num + '&f=' + type + '&r=0&start=' + start;
	  return url + '&callback=?'; 
	}
	
	var requestPage = function(start,key){
		var type= getValueRadio("search_option_mp3");
		key = key.replace(/\+/g,' ');
		url=base_url+'mp3/search/#play_song/'+type+'/'+start+'/' + encodeURIComponent(key);
		requestURL(url);
	}
	
	var requestURL = function(url_change)
     {
	     window.location.href=url_change; 
     };
     
	var Pagination = function(offset, numOfPage, currentPage){
		var pageStart = parseFloat(currentPage) - parseFloat(offset);
		var pageEnd = parseFloat(currentPage) + parseFloat(offset);
		var numPage = new String();
		if(numOfPage < 1) return false;
		numPage += '<ul id="pagi">';
		if(currentPage > 1) numPage += '<li class="previous"><a href="javascript:;" name="page'+(parseFloat(currentPage) - 1)+'">&laquo;</a></li>';
		else numPage += '<li class="previous-off">&laquo;</li>';
		if(currentPage > (offset + 1)) numPage += '<li><a href="javascript:;" name="page1">1</a></li><li class="spacing-dot"> ... </li>';
		for(i = 1; i <= numOfPage; i++){
			if(pageStart <= i && pageEnd >= i){
				if(i == currentPage + 1) numPage += '<li class="active">' + i + '</li>';
				else numPage += '<li><a href="javascript:;" name="page' + i + '">' + i + '</a></li>';
			}
		}
		if(numOfPage > pageEnd) numPage += '<li class="spacing-dot"> ... </li>';//<li><a href="javascript:;" name="page'+numOfPage+'">'+numOfPage+'</a></li>';
		if(currentPage < numOfPage) numPage += '<li class="next"><a href="javascript:;" name="page'+(parseFloat(currentPage) + 2)+'">&raquo;</a></li>';
		else numPage += '<li class="next-off">&raquo;</li>';
		numPage += '</ul>';
		return numPage;
	}
})(jQuery);;
