jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('strong');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 });
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

function urlencode(str){
return encodeURIComponent(str);
}


dontFromFocus = false;
lastType = 'from';
fromCounter = 0;

var selected = {from: -1, to: -1};


$(function(){
	$('#from').keyup(function(e){
		var code = e.keyCode || e.which;
		return handleKeyCode('from', code, e);
	});

	$('#to').keyup(function(e){
		var code = e.keyCode || e.which;
		return handleKeyCode('to', code, e);
	});
	
	$('#InputFieldOrBubble_from div.Place p').dblclick(function(){
		whenDbClickComme('from');
	});
	
	$('#InputFieldOrBubble_to div.Place p').dblclick(function(){
		whenDbClickComme('to');
	});
	
	$('div.Tips a.Close').click(function(){
		$('div.Tips').slideUp('fast');
		return false;
	});
	
	$('div.Head a.Blue').click(function(){
		$('div.Tips').slideDown( 'fast' );
		return false;
	});
	
	if( isFound == false ){
		setTimeout(refreshNew, 2000);
	}
	
	$('#from').focus();
});



if( typeof(refreshLastId) == "undefined" ){
	refreshLastId = false;
}

timesShowed = 0;
maxTimesShow = 100;

function refreshNew(){
	$.getJSON('/refreshbus.json', { l:refreshLastId}, function(data){
		refreshLastId = data.l;
		max = data.d.length;
		for( var i=0; i<max;i++){
			addRefreshRecord(data.d[i].fid,data.d[i].tid,data.d[i].f,data.d[i].t);
		}
		timesShowed++;
		if( timesShowed < maxTimesShow ){
			setTimeout("refreshNew()", 2000 + timesShowed*100 );
		}
	});		
}


function addRefreshRecord(selected_from, selected_to, from_name, to_name){
	var $timerUpdateElement = $('#TimerUpdateElement');
	
	var new_html = '<a href="' + module + '?selected_from=' + selected_from + '&selected_to=' + selected_to + '">'
		+ from_name + '<span class="To"> - ' + to_name + '</span></a>';
	
	$(new_html)
		.insertBefore($timerUpdateElement.find('a:first'))
		.hide()
		.slideDown('slow');
	
	$timerUpdateElement.find('a:not(.marked-for-deletion):last')
		.addClass('marked-for-deletion')
		.slideUp('slow', function(){ $(this).remove() });
}

//iekrāso selektēto
function highlightLi($collection, idx){
	$collection
		.removeClass('ac_over')
		.eq(idx)
			.addClass('ac_over');
}

//pārvieto selekciju uz izvēlēto indeksu
function moveSelection(type, idx){
	var $list = $('#'+type+'_list li:not(.Header)')
	var maxIdx = $list.length - 1;
	
	if(idx > maxIdx){
		idx = 0;
	} else if(idx < 0){
		idx = maxIdx;
	}
	selected[type] = idx;
	
	highlightLi($list, idx);
}

//noņem iezīmējumu
function removeSelection(type){
	$('#'+type+'_list li').removeClass('ac_over');
	selected[type] = -1;
}

function handleKeyCode(type, code, e){
	var doSearch = true;

	switch(code){
		case 13: //enter
			doSearch = false;
			addBubble( lastType );
			return;
		break;
		case 38: //upArrow
			doSearch = false;
			moveSelection(type, selected[type] - 1);
		break;
		case 40: //downArrow
			doSearch = false;
			moveSelection(type, selected[type] + 1);
		 break;
	}

	if( doSearch ){
		Suggest(type);
	}

	return doSearch;
}



function checkForBubble(noFlash){
	var error = false;

	$.each(['from', 'to'], function(idx, type){
		if($('#selected_' + type).val() == -1){
			var $list = $('#' + type + '_list');
			if( !$list.is(':visible') ){
				 $list.slideDown('slow');
			}
			$list.find('li.Header').addClass('Alert').fadeOut('fast').fadeIn('fast');
			$('#' + type).focus();
			error = true;
			return false; //break out of $.each()
		}
	});

	return !error;
}


alreadySentAjax = false;
searchWordHightlight = '';
jsondata = new Object();



function Suggest(type){
	selected[type] = -1;
	lastType = type;
	var $type = $('#' + type);
	var val = $type.val();
	var $list = $('#' + type + '_list');
	var $ul = $list.find('ul');

	searchWordHightlight = urlencode( val );
	

	if(val.length >= 2 && !alreadySentAjax){
		var url = '?c=autocomplete&type='+type+'&q='+urlencode( val );
		alreadySentAjax = true;
		$.getJSON(url, function(data){

			jsondata = data;
			max = jsondata.data.length;
			
			$ul.html('');
			if( max > 0) $ul.append('<li class="Header">'+uiLangChoose+':</li>');
			
			var ad_class;
			for( i=0; i<max; i++ ){
				ad_class = (i % 2 == 0) ? 'ac_even' : 'ac_odd';
				$ul.append('<li id="'+type+'pid_'+jsondata.data[i].id+'" class="'+ad_class+'">'+jsondata.data[i].p+'</li>');
			}
			
			
			if( !$list.is(':visible') ){
				$list.slideDown('slow');
			}
			
			alreadySentAjax = false;
			oldCssClass = '';
		    
		    $ul.find('li:not(.Header)')
		    	.css("cursor", "pointer")
		    	.mouseenter(function(){
					moveSelection( type, $ul.find('li:not(.Header)').index(this) );
		    	}).mouseleave(function(){
		    		removeSelection( type );
			    }).click(function(){
		    		addBubble( type, $(this));
		    		return;
		    	});
  
		    $ul.find('li:not(.Header)').highlight( val );
		});
	
	}
	
	if( val.length < 2 ){
		$list.hide();
		$type.show();
	}

}
		
function addBubble(type, obj){
	obj = obj || $('#' + type + '_list li:not(.Header):eq(' + selected[type] + ')');
	if(obj.length == 0) return;

	var place_id = obj.attr("id").split('_');

	var short_string = '';
	max = jsondata.data.length;
	for(var i=0; i<max; i++){
		if( jsondata.data[i].id == place_id[1] ){
			short_string = jsondata.data[i].s;
			break;
		}
	}
	
	if( short_string == '' ){
		short_string = obj.text();
	}
	
	$('#selected_'+type).val(place_id[1]);
	
	$('#'+type).hide();
	$('#InputFieldOrBubble_'+type+' div.Place').show();
	$('#'+type+'_list').slideUp('fast');
	$('#InputFieldOrBubble_'+type+' div.Place p').html(short_string+'<a title="Mainīt" onclick="closeBubbleShowInput(\''+type+'\');" href="javascript:void(0);"></a>').dblclick(
		function(){
			whenDbClickComme(type);
		}
	);

	if(checkForBubble()){
		$('#to').closest('form').submit();
	}
	return false;
}
		
		
function whenDbClickComme(type){
	$('#InputFieldOrBubble_'+type+' div.Place').hide();
	$('#'+type).show().select().keyup();
	$('#'+type+'_list').slideUp('fast');
	$('#selected_'+type).val('-1');
}

function closeBubbleShowInput(type){
	$('#InputFieldOrBubble_'+type+' div.Place').hide();
	$('#'+type).val('').show().focus();
	$('#selected_'+type).val('-1');
}

