﻿/**
 * AutoComplete Field - JavaScript Code
 *
 * This is a sample source code provided by fromvega.
 * Search for the complete article at http://www.fromvega.com
 *
 * Enjoy!
 *
 * @author fromvega
 *
 */

// global variables for formsearch1
var acListTotal   =  0;
var acListCurrent = -1;
var acDelay		  = 10;
var acURL		  = null;
var acSearchId	  = null;
var acResultsId	  = null;
var acSearchField = null;
var acResultsDiv  = null;
var aResults	  = null;
var aEmptys		  = null;
// global variables for formsearch2
var acListTotal1   =  0;
var acListCurrent1 = -1;
var acDelay1		  = 10;
var acURL1		  = null;
var acSearchId1	  = null;
var acResultsId1	  = null;
var acSearchField1 = null;
var acResultsDiv1  = null;
var aResults1	  = null;
var aEmptys1		  = null;

function setAutoComplete(field_id, results_id, get_url){
	
	// initialize vars
	acSearchId  = "#" + field_id;
	acResultsId = "#" + results_id;
    acURL 		= get_url;
	if(aResults == null)
			aResults = new Array();
	if(aEmptys == null)		
			aEmptys = new Array();
	// create the results div    
    $("body").append('<div id="' + results_id + '"></div>');
 
	// register mostly used vars
	acSearchField	= $(acSearchId);
	acResultsDiv	= $(acResultsId);
	
	// reposition div
	repositionResultsDiv(acSearchField);
	
	// on blur listener
    
    acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });  

	// on key up listener
	acSearchField.keyup(function (e) {
		// get keyCode (window.event is for IE)
		var keyCode =  e.which;
		var lastVal = acSearchField.val();
		var key = lastVal.toLowerCase();
		// check an treat up and down arrows
		if(updownArrow(keyCode)){
			return;
		}
		// check for an ENTER or ESC
		if(keyCode == 13 || keyCode == 27 ){
			clearAutoComplete();
			return;
		}
		
		if(key == ''){
			clearAutoComplete();
			return;
		}
		setTimeout(function () {autoComplete(key)}, acDelay);
	});

}

// treat the auto-complete action (delayed function)
function autoComplete(lastValue)
{
	var tk = acSearchField.val();
    repositionResultsDiv(acSearchField);
	// if it's empty clear the resuts box and return
	if(tk == ''){
		clearAutoComplete();
		return;
	}
	// if it's equal the value from the time of the call, allow
    tk = tk.toLowerCase();
	if(lastValue != tk){
		return;
	}
    if( aResults[lastValue])
		{
			//get json data
			json = aResults[lastValue];
			var ansLength = acListTotal = json.length;
	
			// if there are results populate the results div
			if(ansLength > 0){
	
				var newData = '';
	
				// create a div for each result
				for(i=0; i < ansLength; i++) {
					newData += '<div class="unselected">' + json[i] + '</div>';
				}
	
				// update the results div
				acResultsDiv.html(newData);
				acResultsDiv.css("display","block");
				
				// for all divs in results
				var divs = $(acResultsId + " > div");
			
				// on mouse over clean previous selected and set a new one
				divs.mouseover( function() {
					divs.each(function(){ this.className = "unselected"; });
					this.className = "selected";
				})
				// on click copy the result text to the search field and hide
				divs.click( function() {
					acSearchField.val($(this).text());
					clearAutoComplete();
                    if(acSearchId =='#keyword'){
                       search_onclick(document.forms.frmSearch2, document.getElementById('searchType2'));
                    } else {
                       search_onclick(document.forms.frmSearch, document.getElementById('searchType'));
                    }
				});
	
			} else {
				clearAutoComplete();
			}
			return;
		}else if(in_array(lastValue,aEmptys)){
            clearAutoComplete();
			return;	
		}
    
	//Create URL request
	var url = acURL;
	tk = encodeURIComponent(lastValue);
    url = url + "?query=" + tk;
   
    if(acSearchId =='#keyword'){
       url = url + "&type=" + $('#searchType2').val();
    } else {
       url = url + "&type=" + $('#searchType').val();
    }
	url = url + "&callback=?";//Config
    
   // document.getElementById('id_msg').innerHTML = 	url;
    $.getJSON( url , function( data ){
        json = data;
       	if(aResults == null)
			aResults = new Array();
		if(aEmptys == null)		
			aEmptys = new Array();	
			
		tk = lastValue.toLowerCase();
		var ansLength = acListTotal = json.length;
		
		if(json[0] == "null"){
			aEmptys.push(tk);
			clearAutoComplete();
			return ;
		}
		
		aResults[tk] = json;
		// if there are results populate the results div
		if(ansLength > 0){
            var newData = '';
			
			// create a div for each result
			
			for(i=0; i < ansLength; i++) {
				newData += '<div class="unselected">' + json[i] + '</div>';
			}
			
			// update the results div
			acResultsDiv.html(newData);
			acResultsDiv.css("display","block");
			
			// for all divs in results
			var divs = $(acResultsId + " div");
			
			// on mouse over clean previous selected and set a new one
			divs.mouseover( function() {
				divs.each(function(){ this.className = "unselected"; });
				this.className = "selected";
			})
			// on click copy the result text to the search field and hide
			divs.click( function() {
				acSearchField.val($(this).text());				
				clearAutoComplete();
                if(acSearchId =='#keyword'){
                    search_onclick(document.forms.frmSearch2, document.getElementById('searchType2'));
                } else {
                    search_onclick(document.forms.frmSearch, document.getElementById('searchType'));
                }
			});
		
		}else{
			clearAutoComplete();
			return;
		}
  }
  );
}
function in_array(value, array){	
    for (i = array.length -1 ; i >= 0 ; i--)
       if(value.indexOf(array[i]) != -1 )
          return true;  
    return false;  
}
// clear auto complete box
function clearAutoComplete()
{
	acResultsDiv.html('');
	acResultsDiv.css("display","none");
}
// reposition the results div accordingly to the search field
function repositionResultsDiv(acSearchField)
{
	var sf_pos    = acSearchField.offset();
	var sf_top    = sf_pos.top;
	var sf_left   = sf_pos.left;

	// get the field size
	var sf_height = acSearchField.height();
	var sf_width  = acSearchField.width();

	// apply the css styles - optimized for Firefox
	acResultsDiv.css("position","absolute");
	acResultsDiv.css("left", sf_left - 2);
	acResultsDiv.css("top", sf_top + sf_height + 5);
	acResultsDiv.css("width", sf_width - 2);
}


// treat up and down key strokes defining the next selected element
function updownArrow(keyCode) {
	if(keyCode == 40 || keyCode == 38){

		if(keyCode == 38){ // keyUp
			if(acListCurrent == 0 || acListCurrent == -1){
				acListCurrent = acListTotal-1;
			}else{
				acListCurrent--;
			}
		} else { // keyDown
			if(acListCurrent == acListTotal-1){
				acListCurrent = 0;
			}else {
				acListCurrent++;
			}
		}

		// loop through each result div applying the correct style
		acResultsDiv.children().each(function(i){
			if(i == acListCurrent){
				acSearchField.val($(this).text());
				this.className = "selected";
			} else {
				this.className = "unselected";
			}
		});

		return true;
	} else {
		// reset
		acListCurrent = -1;
		return false;
	}
}

// For form search 2
function setAutoComplete1(field_id, results_id, get_url){
	
	// initialize vars
	acSearchId1  = "#" + field_id;
	acResultsId1 = "#" + results_id;
    acURL1 		= get_url;
	if(aResults1 == null)
			aResults1 = new Array();
	if(aEmptys1 == null)		
			aEmptys1 = new Array();
	// create the results div
	$("body").append('<div id="' + results_id + '"></div>');

	// register mostly used vars
	acSearchField1	= $(acSearchId1);
	acResultsDiv1	= $(acResultsId1);
	
	// reposition div
	repositionResultsDiv(acResultsDiv1);
	
	// on blur listener
        
    acSearchField1.blur(function(){ setTimeout("clearAutoComplete1()", 200) });
    // on key up listener
	//if($.browser.msie)
	acSearchField1.keyup(function (e) {
		// get keyCode (window.event is for IE)
		var keyCode =  e.which;
		var lastVal = acSearchField1.val();
		var key = lastVal.toLowerCase();
		// check an treat up and down arrows
		if(updownArrow1(keyCode)){
			return;
		}
		// check for an ENTER or ESC
		if(keyCode == 13 || keyCode == 27 ){
			clearAutoComplete1();
			return;
		}
		
		if(key == ''){
			clearAutoComplete1();
			return;
		}
		setTimeout(function () {autoComplete1(key)}, acDelay);
	});

}

// treat the auto-complete action (delayed function)
function autoComplete1(lastValue)
{
	var tk = acSearchField1.val();
    repositionResultsDiv(acSearchField1);
	// if it's empty clear the resuts box and return
	if(tk == ''){
		clearAutoComplete1();
		return;
	}

	// if it's equal the value from the time of the call, allow
    tk = tk.toLowerCase();
	if(lastValue != tk){
		return;
	}
   
	if( aResults1[lastValue]  )
		{
			//get json data
			json = aResults1[lastValue];
			var ansLength = acListTotal1 = json.length;
	
			// if there are results populate the results div
			if(ansLength > 0){
	
				var newData = '';
	
				// create a div for each result
				for(i=0; i < ansLength; i++) {
					newData += '<div class="unselected">' + json[i] + '</div>';
				}
	
				// update the results div
				acResultsDiv1.html(newData);
				acResultsDiv1.css("display","block");
				
				// for all divs in results
				var divs = $(acResultsId1 + " > div");
			
				// on mouse over clean previous selected and set a new one
				divs.mouseover( function() {
					divs.each(function(){ this.className = "unselected"; });
					this.className = "selected";
				})
				// on click copy the result text to the search field and hide
				divs.click( function() {
					acSearchField1.val($(this).text());
					clearAutoComplete1();
                    if(acSearchId1 =='#keyword'){
                       search_onclick(document.forms.frmSearch2, document.getElementById('searchType2'));
                    } else {
                       search_onclick(document.forms.frmSearch, document.getElementById('searchType'));
                    }
				});
	
			} else {
				clearAutoComplete1();
			}
			return;
		}else if(in_array(lastValue,aEmptys1)){
            clearAutoComplete1();
			return;	
		}
	//Create URL request
	var url = acURL1;
	tk = encodeURIComponent(lastValue);
    url=url+"?query="+tk;
    if(acSearchId1 =='#keyword'){
       url=url+"&type="+$('#searchType2').val();
    } else {
       url=url+"&type="+$('#searchType').val();
    }
	url=url+"&callback=?";//Config
	
 
    //document.getElementById('id_msg').innerHTML = 	url;
    $.getJSON( url , function( data ){
        json = data;
       	if(aResults1 == null)
			aResults1 = new Array();
		if(aEmptys1 == null)		
			aEmptys1 = new Array();	
			
		tk = lastValue.toLowerCase();
		var ansLength = acListTotal1 = json.length;
		
		if(json[0] == "null"){
			aEmptys1.push(tk);
			clearAutoComplete1();
			return ;
		}
		
		aResults1[tk] = json;
		// if there are results populate the results div
		if(ansLength > 0){
            var newData = '';
			
			// create a div for each result
			
			for(i=0; i < ansLength; i++) {
				newData += '<div class="unselected">' + json[i] + '</div>';
			}
			
			// update the results div
			acResultsDiv1.html(newData);
			acResultsDiv1.css("display","block");
			
			// for all divs in results
			var divs = $(acResultsId1 + " div");
			
			// on mouse over clean previous selected and set a new one
			divs.mouseover( function() {
				divs.each(function(){ this.className = "unselected"; });
				this.className = "selected";
			})
			// on click copy the result text to the search field and hide
			divs.click( function() {
				acSearchField1.val($(this).text());				
				clearAutoComplete1();
                if(acSearchId1 =='#keyword'){
                   search_onclick(document.forms.frmSearch2, document.getElementById('searchType2'));
                } else {
                   search_onclick(document.forms.frmSearch, document.getElementById('searchType'));
                }
			});
		
		}else{
			clearAutoComplete1();
			return;
		}
  }
  );
}

// clear auto complete box
function clearAutoComplete1()
{
	acResultsDiv1.html('');
	acResultsDiv1.css("display","none");
}

// treat up and down key strokes defining the next selected element
function updownArrow1(keyCode) {
	if(keyCode == 40 || keyCode == 38){

		if(keyCode == 38){ // keyUp
			if(acListCurrent1 == 0 || acListCurrent1 == -1){
				acListCurrent1 = acListTotal1-1;
			}else{
				acListCurrent1--;
			}
		} else { // keyDown
			if(acListCurrent1 == acListTotal1-1){
				acListCurrent1 = 0;
			}else {
				acListCurrent1++;
			}
		}

		// loop through each result div applying the correct style
		acResultsDiv1.children().each(function(i){
			if(i == acListCurrent1){
				acSearchField1.val($(this).text());
				this.className = "selected";
			} else {
				this.className = "unselected";
			}
		});

		return true;
	} else {
		// reset
		acListCurrent1 = -1;
		return false;
	}
}
// ham xu ly su kien khi nhan vao nut bao loi bai hat.
function reportError(p_media_id, url){
    if(!confirm('Bạn có muốn báo link nhạc này hỏng?'))
    return;
    //Create URL request
	var url = url + "/webservices/reportError.php?id="+p_media_id;
    url = url + "&callback=?";//Config
	$.getJSON( url , function( data ){
        alert( data[0]);
    });
}

