/********************************************************
Position the dropdown div below the input text field.
********************************************************/
var positionDiv = function(refObj, div)
{
	var el = refObj;
	var x = 0;
	var y = el.offsetHeight;

	//Walk up the DOM and add up all of the offset positions.
	while (el.offsetParent && el.tagName.toUpperCase() != 'BODY')
	{
		x += el.offsetLeft;
		y += el.offsetTop;
		el = el.offsetParent;
	}

	x += el.offsetLeft;
	y += el.offsetTop + 1;

	div.style.left = x + 'px';
	div.style.top = y + 'px';
};

/********************************************************
Change the opacity for different browsers
********************************************************/
var changeOpac = function (opacity, id) {
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

/********************************************************
Fade in/out implement.
********************************************************/
var opacity = function (id, opacStart, opacEnd, millisec) {
	var object = document.getElementById(id).style;
	if( object.opacity == opacEnd || 
		object.MozOpacity == opacEnd || 
		object.KhtmlOpacity == opacEnd || 
		object.filter == "alpha(opacity=" + opacEnd + ")" || 
		(object.opacity === undefined && object.MozOpacity === undefined && object.KhtmlOpacity === undefined) && object.filter == ""){
		return;
	}

	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer ++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++)
			{
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer ++;
		}
	}
} 

/********************************************************
Display the dropdown. Pretty straightforward.
********************************************************/
var showDiv = function(div)
{
	div.style.display = 'block';
	//opacity('search_result', 0, 90, 1000);
};

/********************************************************
Hide the dropdown and clear any highlight.
********************************************************/
var hideDiv = function(div)
{
	//opacity('search_result', 90, 0, 1000);
	div.style.display = 'none';
};

/********************************************************
Add a new tabel into DIV to display the responsed data.
********************************************************/
var appendRow = function(values){
	var oDiv = document.createElement('div');
	oDiv.className = 'result_row';
	oDiv.onmouseover = function(){oDiv.className = 'result_row_highlight'};
	oDiv.onmouseout = function(){oDiv.className = 'result_row'};
	oDiv.onclick = function(){window.location = 'play.php?vid=' + values.indexer;};

	var oTB = document.createElement("table");
	oTB.width = 355;
	oTB.border = 0;
	oTB.cellSpacing = 1;
	oTB.cellPadding = 1;
	oTB.className = 'result_row';
	var oTR = oTB.insertRow(0);
	var oTD0 = oTR.insertCell(0);
	oTD0.width = 75;
	oTD0.align = "left";
	oTD0.innerHTML = "<img src='../uploads/thumbs/" + values.video_id + ".jpg' width='75' height='58'/>";
	var oTD1 = oTR.insertCell(1);
	oTD1.width = 280;
	oTD1.vAlign = 'top';
	
	var lang = document.getElementById('select_language').value;
	if(lang == 'spa'){
		sCat = 'Categoria';
		sTitle = 'Titulo';
		sTags = 'Etiquetas';
		sLang = 'Idioma';
	}else{
		sCat = 'Category';
		sTitle = 'Title';
		sTags = 'Tags';
		sLang = 'Language';
	}
	
	oTD1.innerHTML = "<strong>&nbsp;" + sCat + ":</strong>&nbsp;" + values.channel + 
					 "<br/><strong>&nbsp;" + sTitle + ":</strong>&nbsp;" + values.title + 
					 "<br/><strong>&nbsp;" + sTags + ":</strong>&nbsp;" + values.tags + 
					 "<br/><strong>&nbsp;" + sLang + ":</strong>&nbsp;" + values.lang;
	
	oDiv.appendChild(oTB);
	document.getElementById('search_result').appendChild(oDiv);
}

/********************************************************
Remove all child from DIV.
********************************************************/
var removeRows = function(){
	var kids = document.getElementById('search_result').childNodes;
	var len = kids.length;
	for (j=0; j < len; j++) {
    	document.getElementById('search_result').removeChild(kids[0]);
	}
}

var onResultDivKeyup = function(keyEvent){
	var keyEvent = (keyEvent) ? keyEvent : window.event;
	if (!$.browser.msie) {
		keyEvent.preventDefault(); //firefox's
	} 

	if(keyEvent.keyCode == 40 || keyEvent.keyCode == 38){
		var kids = document.getElementById('search_result').childNodes;
		if(kids === undefined) return false;
		if (kids.length !== undefined){
			var hasHighLight = false;
			for(var i=0; i<kids.length; i++){
				if (kids[i].className == 'result_row_highlight'){
					kids[i].className = 'result_row';
					if(keyEvent.keyCode == 40){ //DOWN
						var j = ((i + 1) > kids.length-1) ? 0 : (i+1);
					}
					if(keyEvent.keyCode == 38){ //UP
						var j = ((i - 1) < 0) ? (kids.length-1) : (i-1);
					}
					kids[j].className = 'result_row_highlight';
					hasHighLight = true;
					break;
				}
			}
			if(!hasHighLight){ 
				kids[0].className = 'result_row_highlight'; 
			}
		}else{
			kids.className = 'result_row_highlight';
		}
	}

	if(keyEvent.keyCode == 13){ //ENTER
		var kids = document.getElementById('search_result').childNodes;
		if(kids === undefined) return;
		if (kids.length !== undefined){
			for(var i=0; i<kids.length; i++){
				if (kids[i].className == 'result_row_highlight'){
					kids[i].onclick();
					hideDiv(document.getElementById('search_result'));
					break;
				}
			}
		}else{
			if(kids.className == 'result_row_highlight'){
				hideDiv();
				kids.onclick(document.getElementById('search_result'));
			}
		}
	}
	return true;
}

//var prefix = new String("<input type=hidden id='select_language' value='***'/>");
var prefix = new String("");
var last_seq = 0;

$(document).ready(function() {
	document.getElementById('keyword').focus();

	$('#keyword').keyup(function(e){
		var keyword = document.getElementById('keyword').value;
		last_seq ++;
		
		if (e.which == 40 || e.which == 38){ // key DWON/UP
			document.getElementById('search_result').focus();
			e.keyCode = e.which;
			onResultDivKeyup(e);
			return;
		}
		
		if(keyword == ""){ 
			removeRows();
			hideDiv(document.getElementById('search_result'));
			return;
		}
		
		$.ajax({
			url: 'search.php',
			type: 'POST',
			data: "keyword=" + keyword + "&type=" + document.getElementById('type').value + "&source=ajax&seq=" + last_seq,
			dataType: 'text',
			timeout: 30000,
			success: function(text){
				var res = new String(text);
				res = res.substr(prefix.length);
				
				var searchRes = xml2json.parser(res);
				if(searchRes.videos.seq == last_seq){
					var videos = searchRes.videos;
					if(videos.video == undefined) return;
					
					removeRows();
					document.getElementById('search_result').style.height = "";
					if(videos.video instanceof Array){
						if(videos.video.length > 10){document.getElementById('search_result').style.height = 640;}
						for(var i=0; i<videos.video.length; i++){
							appendRow({video_id:videos.video[i].videoid, 
									   channel:videos.video[i].channel, 
									   title:videos.video[i].title, 
									   indexer:videos.video[i].indexer,
									   tags:videos.video[i].tags,
									   lang:videos.video[i].lang});	
						}
					}else{
						appendRow({video_id:videos.video.videoid, 
								   channel:videos.video.channel, 
								   title:videos.video.title, 
								   indexer:videos.video.indexer,
								   tags:videos.video.tags,
								   lang:videos.video.lang});	
					}
					
					positionDiv(document.getElementById('keyword'), document.getElementById('search_result'));
					showDiv(document.getElementById('search_result'));
				}
			}
		});
		
	});
});
