/**
 * @author User
 */
/**
 * autocomplete fill with tickers
 * @param {Object} inputText
 */

$(document).ready(function(){
	
	autoFillSearchText();
	
	autoSearchTicker( $("#tickerSo") );
	$("#js_searchBtn").click( function(){
		 if( $("#tickerSo").val() != "" && $("#tickerSo").val() != 'Enter company or symbol (Single)' && $("#tickerSo").val().toUpperCase() != ticker.toUpperCase()  ){		 
			 ticker = $("#tickerSo").val();
			 if( typeof(isLandingPage) != 'undefined' && isLandingPage == true ){
			 } else {
				 getAssetDetail( ticker );
			 }			
			 getAssetsHistoricalPrices( ticker );
		 } else {
		 	autoFillSearchText();
		 }
		return false;
	})
})//end ready

function autoFillSearchText(){
	if( !ticker ){
				$("#tickerSo").val( 'Enter company or symbol (Single)' );
				$("#tickerSo").addClass("gray_size12");			
			} else {				
				$("#tickerSo").val( ticker.toUpperCase() ).removeClass('gray_size12');
	}
}
//////////////////////autocomplete///////////////////
function split(val) {
	return val.split(/,\s*/);
}
function extractLast(term) {
	return split(term).pop();
}
function heighligh(value, term){
	return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
}
function autoSearchTicker( inputText ){
	$(inputText).autocomplete({
		source: function(request, response) {
		var settings = {
				url:   rest.getHost() + "assets/search/keyword", 
				dataType: "json",
				data: {					
					limit: 10,				
					q: extractLast(request.term)
					
				},
				success: function(data) {
					response($.map(data, function(item) {
						return {
							label: heighligh("<div><span class='assetSymbol'>"+ item.ticker +"</span><span class='assetName'>"+ item.assetName+"</span><span class='assetType' >"+item.assetType+"</span></div>",request.term),
							value: item.ticker
						}
					  }
					))					
				}
			}
		rest.ajaxRestGet( settings );		
		},
		minLength: 1,
		focus: function() {
			// prevent value inserted on focus
			return false;
		},
		select: function(event, ui) {
			this.value =ui.item.value;
			$("#js_searchBtn").click();	
			return false;
		}
	})	
	.keypress(function( event ){
		//klgDebug.log(event.keyCode );
		if( event.keyCode == 13 ){
			var item = $( ".ui-menu-item" ).eq(0);	
			if( item.length > 0 ){
				item = item.data( "item.autocomplete" );
				$(this).val( item.value );
				$("#js_searchBtn").click();	
				$(inputText).autocomplete( "close" );
			} 
		}
	})	
	.click( function(event){
		$(this).val( '' );
	})
}
