var char_min = 2;

// *** form specific vars, override where required ***
var form_ids = new Array('search_all');
var data_ids = new Array('search_data');
var list_tps = new Array(0,0);
var list_id  = 'stock_list';

var search_index = 0; // if page contains multiple form instances determine which one is active

var search_val;
var stocks = new Array();
var stock_no = -1;
var search_limit = 50;

var e_focus = false;

// var to hold current tr being highlightedf
var tr_class = '';

/************************************************************
 * Display specific vars for 'in page' stock table	    *
 * Override as necessary				    *
 ************************************************************
 * results_table_id  : selector for the results table	    *
 * results_table_body: selector for the body results table  *
 * error_box         : selector for the error box	    *
 * error_msg_box     : selector for the error msg box	    *
 * pagination_row    : selector for the pagination row      *
 * offset_field	     : selector for the offset field        *
 * key_id	     : selector for the table key	    *
 * loading_img	     : selector for the loading image	    *
 * results_box       : boolean - displaying results in box  *
 ************************************************************/

var results_table_id, results_table_body, error_box, error_msg_box, pagination_row, offset_field, key_id, loading_img, results_box, fund_chart_link;


if( !this['getElement'] ){
	//[matt w] Retreives element by id or returns false if element doesn't exist
	function getElement(e){
		if( !document.getElementById ) return false;
		return ( !document.getElementById(e) )? false : document.getElementById(e);
	}
}


// highlight list rows
function highlight(no, status){
	
	if(no != stock_no) stock_no = parseInt(no);
	
	var $tr = $('tr#tr_'+stock_no);
	
	//var tr = getElement('tr_' + stock_no);
	if($tr){
		//if(status == true){
			//tr.scrollIntoView((tr.parentNode).id); 
		//}
		
		tr_class = $tr.attr('class');
		$tr.addClass('highlight');
	}

}

// unhighlight list rows
function unhighlight(no){

	var $tr = $('tr#tr_' + stock_no);
	$tr.removeClass('highlight');
	if(tr_class){
		$tr.addClass(tr_class);
	}
	else{
		//set_row_bgs();
	}

}

function set_row_bgs(){
	var $tbody = $('tbody#stock_list_tbody');
	$tbody.children('tr:odd').css('background','').removeClass('even').addClass('odd');
	$tbody.children('tr:even').css('background','').removeClass('odd').addClass('even');
}

function get_evt(e) { return (e)? e : ((window.event) ? event : null); }
function get_node(e){ return (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null); }

// capture keypress event
function capture_keypress(e){
	var evt  = get_evt(e);
	var node = get_node(evt); 

	if(evt){
		var key = evt.keyCode;	
		if(key == 13 && node.type == 'text') stock_selection(stock_no, 'security_details');
	}
}

// capture mouse click, hide search box when clicking outside of search function
function capture_id(e){
	var evt  = get_evt(e);
	var node = get_node(evt);

	if (node.nodeType == 3) node = node.parentNode; // Safari fix

	var d = ( data_ids[search_index] ? data_ids[search_index] : '_' );
	
	var i = d.indexOf('_');
	var m = (i != -1)? d.substr(0, i) : d;	

	if(node.id.indexOf(m) == -1){
		display_box(false, search_index);
	}
}

// capture keyup event
function capture_keyup(e){
	var evt  = get_evt(e);
	var node = get_node(evt); 

	if(evt){
		var key = evt.keyCode;

		// which form is being used?
		if(node.id != data_ids[search_index])
                {
			for(var id in data_ids)
                        {
				if(data_ids[id] == node.id)
                                {
					search_index = id;
					break;
				}
			}
		}

		// perform actions on particular key events
		if((key == 38 || key == 40) && e_focus == true)
                { 
                        // navigate stock list
			// only perform action when element is selected
			if(key == 38 && stock_no > -1) stock_no -= 1; //up
			if(key == 40 && stock_no < stocks.length - 1) stock_no += 1; // down

			highlight(stock_no, true);
		}
                else if(key == 9)
                {
			// tab away from search
			e_focus = false;
		}
                else if(node.id == data_ids[search_index])
                {
			// capture characters entered and perform search
			stock_search(node);
		}
	}
}

// manage client stock selection from list & submit form
function stock_selection(stock, action)
{
	if((e = getElement(form_ids[search_index])) == false || stock == -1) return false;

	var autopost = true, autojs = false;
	var list_updates = {'cmd':'sedol','sedol':stocks[stock]['sedol'],'action':action};

	list_updates[data_ids[search_index]] = stocks[stock]['title'];

	var form_inputs = e.getElementsByTagName('input');

	for(var input in form_inputs){
		var input_name = form_inputs[input].name;

		if(list_updates[input_name]) 
			form_inputs[input].value = list_updates[input_name];
		
		if( input_name == 'stock_selection_autopost' )
			autopost = form_inputs[input].value == 'off' ? false : true;
			
		if( input_name == 'stock_selection_autojs' )
			autojs = form_inputs[input].value == 'off' ? false : form_inputs[input].value;
		
	}

	// override type of search on submission
	// this avoids the fulltext preference for key actions being passed when doing our final sedol lookup

	form_inputs['search_type'].value = 'sedol';

	if( autojs ) this[autojs](action,stocks[stock]['sedol'],stocks[stock]['title'], stocks[stock]['stype']);

	if( autopost ) e.submit();
}

// place stock search into a queue for processing
var search_timeout = undefined; // store delayed function

function stock_search(le)
{
	if((e = getElement(form_ids[search_index])) == false || le.value == 'Search investments') return false;

	if(search_val != le.value)
	{
		$(offset_field).val(0);
	}

	if(search_timeout != undefined)
        {
			clearTimeout(search_timeout);
	}

	search_timeout = setTimeout(function()
        {
		
		search_timeout = undefined;

		search_val = le.value;
		
		if(search_val.length >= char_min)
                {
                        var params = {'method':'complete_search', 'stock_type':'all', 'search_value':escape(search_val)};

                        // select the hidden inputs from the form we are searching with and construct params
                        $("form#" + form_ids[search_index] + " input[type='hidden']").each(function(index, val)
                        {
                            if($(val).attr('name') != 'stock_type' || $(val).attr('name') != 'limit')
                                params[$(val).attr('name')] = $(val).val();

                        });

			// set the callback function used in ajax_functions.js
			ajax_queue_stock.sendAjaxReq_callback = 'ajax_handle_stock_search';
			ajax_queue_stock.use_jsonp = true;

			// partially hide the table to show the use that the search is active again
			if(!results_box)
			{
				$("table#stock_search_results").css({'opacity' : '0.5'});
				$(loading_img).removeClass('box-hide');
			}

			var result = ajax_queue_stock.queue_process(params); // queue process

			if(typeof(result) == 'object'){
				// display previous search
				ajax_handle_stock_search(result);
			}else{
                            if(results_box)
				display_results_box(1); // display loading message

				// start new search
				ajax_queue_stock.start_process(); // attempt to fire process
			}
			
		}else{
                     if(results_box)
			display_results_box(false, -1);
		}
		
	}, 500);
		
}

// form check before accepting submit
function check_search(){
	var e = getElement(data_ids[search_index]);
	if(e == false) return false;
	if(e.value.length < char_min) return false;
	return true;
}

// remove preceding / trailing white space
function str_trim(str){ return str.replace(/^\s+|\s+$/g); }

// link creation
function create_link(id, disp, stock_select_action, target_new){

	var a = document.createElement('a');
	a.setAttribute('id','a_' + id);
	a.className = 'link-cursor';
	//a.setAttribute('href','#');
	if( target_new ){
		a.setAttribute('target','_blank');
	}

	// do we have an image link or textural?
	if(typeof( disp ) == 'object')
		a.appendChild(disp);
	else
		a.innerHTML = disp;

	a.onclick = function(){
		var a_type = stock_select_action ? stock_select_action : ( list_tps[search_index] == 0 ? 'security_details' : 'ajax_deal' ) ;
		stock_selection((this.id).substr(2), a_type); 
	}
	
	return a;
}

var msg_list = {1:'Please Wait',2:'No results found'};
var show_deal_icon = true;
var show_chart_icon = true;
var chart_icon_new_window = false;
var stock_select_action = 'security_details';
var show_over_limit_text = true;
var stock_title = '';

// display / format results within a list format
function display_results_box(stock_list,num_results){

	if((e = getElement(list_id + list_tps[search_index])) == false){
		return false;
	}

	var tbl = document.createElement('table');
	var tbl_body = document.createElement('tbody');
	tbl_body.setAttribute('id','stock_list_tbody');

	stocks = stock_list;

	if(typeof(stock_list) == 'number'){

		// no records have been matched	
		var tr = document.createElement('tr');
		var td = document.createElement('td');

		if( typeof(msg_list[stock_list]) != 'object') {
			var txt = document.createTextNode(msg_list[stock_list]);
			td.appendChild(txt);
		}
		else{
			td.appendChild(msg_list[stock_list]);
		}
		tr.appendChild(td);
		tbl_body.appendChild(tr);
	}else{

		if(stock_list.length > 0){

			// where the search form is going - invest or add to v.holdings
			var frm = getElement(form_ids[search_index]);
			
			// counter for row colour
			var c = 1;
			
			var tr, row, s_epic, s_title, cols;

			// display matched records
			for(var stock in stocks){
		
				if( c <= search_limit && !isNaN(stock) ){

					tr = document.createElement('tr');
					tr.setAttribute('id','tr_' + stock);
					
					row = c%2 ? 'odd' : 'even';
					tr.setAttribute('class',row);
					tr.setAttribute('className',row);
			
					if(highlight){
						tr.setAttribute('onmouseover', 'highlight(' + stock + ', false)');
						tr.onmouseover = function(stock){ highlight((this.id).substr(3), false); }
						tr.setAttribute('onmouseout', 'unhighlight(' + stock + ')');
						tr.onmouseout = function(){ unhighlight((this.id).substr(3)); }
					}
	
					s_epic = ( stocks[stock]['epic_code'] ? highlight_words(stocks[stock]['epic_code'].replace(/[^0-9a-z.]/gi, '')) : '' );
					s_title = highlight_words(stocks[stock]['title'] + ( stocks[stock]['description'] ? ' '+stocks[stock]['description'] : ( stocks[stock]['desc'] ? ' '+stocks[stock]['desc'] : '') ) );
					
					cols = new Array();
					cols[0] = document.createElement('td');
					cols[0].appendChild(create_link(stock, s_title, stock_select_action, false));
					
					cols[1] = document.createElement('td');
					cols[1].appendChild(create_link(stock, s_epic, stock_select_action, false));

                                        if( show_deal_icon ){
			
						var img  = document.createElement('img');

						var deal = (stocks[stock]['internet_allowed'] == 'Y' || list_tps[search_index] == 1)? true : false;

						if( !cols[2] ){
							cols[2] = document.createElement('td');
							cols[2].setAttribute('className','img_links');
                                                        cols[2].setAttribute('style', 'width: 45px; text-align: right;');
						}
						
						if(deal){
							// default to trading ajax handler
							var ref	   = 'Invest';
							var imgRef = 'trade-med';
							var locn   = 'ajax-deal';

                                                        // Create a new link for the deal icon
                                                        var link = document.createElement('a');
                                                        link.setAttribute('href', 'http://online.hl.co.uk/my-accounts/security_deal?sedol=' + stocks[stock]['sedol']);
                                                        link.setAttribute('title', 'Place a deal');
		
							// virtual portfolio
							if ( frm.actn && (frm.actn.value == 'add') )
							{
								ref	   = 'Add';
								imgRef = locn = 'add';
							}
		
							// go to record directly using sedol
							img.setAttribute('id','img_' + stock);
							img.setAttribute('src','http://www.hl.co.uk/__data/assets/image/0016/22723/invest.gif');
							img.setAttribute('alt',ref);
							img.setAttribute('title','Invest now in ' + stocks[stock]['title']);
		
                                                        // Add deal image to the link
                                                        link.appendChild(img);
						}else{
							//img.setAttribute('src', '/img/icons/cancel.gif');
							//img.setAttribute('alt', 'Not tradeable online');
							//img.setAttribute('title', 'This security is not tradeable online');
                                                        
                                                        img = false;
						}
						

                                                if(img != false)
                                                {
						    cols[2].appendChild(link);
                                                }
						
					}

					if( show_chart_icon ){

                                                if( !cols[2] ){
							cols[2] = document.createElement('td');
							cols[2].setAttribute('className','img_links');
                                                        cols[2].setAttribute('style', 'width: 45px; text-align: right;');
						}
						
						var dtl_img = document.createElement('img');
						dtl_img.setAttribute('id','img2_' + stock);
						dtl_img.setAttribute('src','http://www.hl.co.uk/__data/assets/image/0015/22722/graphs.gif');
						dtl_img.setAttribute('alt','View prices & charts');
						dtl_img.setAttribute('title','View prices & charts');
		
						//cols[2] = document.createElement('td');
						//cols[2].setAttribute('className','img_links');
						cols[2].appendChild(create_link(stock, dtl_img, 'security_details', chart_icon_new_window));
						
					}
				
					// stock details button
	//				var img_lnk = document.createElement('a');
	//				var img2    = document.createElement('img');
	
	//				img2.setAttribute('id','img2_' + stock);
	//				img2.setAttribute('src','/img/icons/charts-med.gif');
	//				img2.setAttribute('alt','View prices & charts');
	//				img2.setAttribute('title','View prices & charts');
	//				img_lnk.appendChild(img2);
	//				img_lnk.href = '##security_details?sedol='+stocks[stock]['sedol']+'## ';
					
					
				
					for(var td in cols) tr.appendChild(cols[td]);
						
					tbl_body.appendChild(tr);
	
					c++;
				}
				else continue;
					
			}
		}
	}

	remove_child_nodes(e);
	
	// add text if there's more results than the limit
	if( show_over_limit_text && num_results && search_limit < num_results )
	{
		var search_form = getElement(form_ids[search_index]);
		
		var msg = document.createElement('p');
		msg.style.margin=0;
		msg.style.marginBottom='4px';
		msg.innerHTML = 'Your search has returned more than 50 results.';
		msg.appendChild( document.createElement('br') );
		msg.innerHTML += 'Please narrow your search'
						+( search_form ? ', or ' : '.' );
		if( search_form )
		{
			var view_a = document.createElement('a');
			view_a.className = "link link-headline link-cursor";
			view_a.innerHTML = 'view all results';
			view_a.onclick = function(){ search_form.submit(); }
			msg.appendChild( view_a );
		}
		e.appendChild(msg);
		msg = document.createElement('hr');
		msg.style.marginLeft = '-5px';
		e.appendChild(msg);
	}

	tbl.appendChild(tbl_body);
	e.appendChild(tbl);
	
	// add text if there's more results than the limit
	if( show_over_limit_text && num_results && search_limit < num_results )
	{
		msg = document.createElement('hr');
		msg.style.marginLeft = '-5px';
		e.appendChild(msg);
		
		msg = document.createElement('p');
		msg.style.margin=0;
		msg.style.marginTop='4px';
		msg.innerHTML = 'Your search has returned more than 50 results.';
		msg.appendChild( document.createElement('br') );
		msg.innerHTML += 'Please narrow your search'
						+( search_form ? ', or ' : '.' );
		if( search_form )
		{
			var view_a = document.createElement('a');
			view_a.className = "link link-headline link-cursor";
			view_a.innerHTML = 'view all results';
			view_a.onclick = function(){ search_form.submit(); }
			msg.appendChild( view_a );
		}
		e.appendChild(msg);

	}
	
	display_box(true, -1);
}

/**
 * Used to display stock results within the page
 * stock_list  - object containing results | set to 2 if no results are returned
 * num_results - int - number of results returned
 */

function display_results_page(stock_list, num_results)
{
   /**
    * The table contains a couple of hidden rows at the top which get cloned in the script below
    * Delete everything but the rows we need to clone.
    */

	$(results_table_body).each(function(index, val)
	{
		if(index > 2)
		{
			$(this).remove();
		}
	});

        // No results returned - show error message
	if(stock_list == 2)
	{
		if($(error_box + " " + error_msg_box).html() == '')
		{
			$(error_box).show();
			$(error_msg_box).append('<strong>0 results found. Please try a different term or call us on 0117 900 9000.</strong>').fadeIn();
		}
	}
	// We have results, lets begin processing.
	else
	{
                // Hide any associated errors
                hide_error();

		// Loop through each of the results returned
		$.each(stock_list, function(index, val)
		{
			// The first row in the tbody is a template - clone it for this result and add the odd or even class.
			var row		= $(results_table_body + ":first").clone();
			row_odd_eve = (index%2) ? '' : 'table-even';

			// Add mouseover event to table row
			$(row).addClass(row_odd_eve).mouseover(function()
			{
				$(this).addClass('highlight');	
			}).mouseout(function()
			{
				$(this).removeClass('highlight');
			});

			// Make the row visible
			$(row).removeClass('box-hide');

			// Create epic title and identifier variables
			var identifier	= ( val['epic_code'] ? highlight_words(val['epic_code'].replace(/[^0-9a-z.]/gi, '')) : '' );
			var title	= highlight_words(val['title'] + ( val['description'] ? ' ' + val['description'] : ( val['desc'] ? ' ' + val['desc'] : '') ) );
                        var type        = val['stype'];

			// Should the identifier be the eipc or the sedol?
			if(!identifier.length)
			{
				if(val['stock_ticker'] != null)
				{
					identifier = highlight_words(val['stock_ticker'].replace(/[^0-9a-z-.]/gi, ''));
				}
				else
				{
					identifier = (val['sedol'].length) ? val['sedol'] : '';
				}
			}

			// Create new vars for the chart and dealing images
			var chart_img, deal_img, vp_img;

			// Create and assign attributes to the chart image
			if( show_chart_icon )
			{
				chart_img = $(document.createElement('img'));
				$(chart_img).attr({     'src'	: 'http://www.hl.co.uk/__data/assets/image/0015/22722/graphs.gif',
							'alt'	: 'View prices & charts',
							'title'	: 'View prices & charts',
							'id'	: 'img_2_' + val['sedol'] });
			}

			// Create and assign attributes to the deal image
			if( show_deal_icon )
			{
				deal_img = $(document.createElement('img'));
				var deal = (val['internet_allowed'] == 'Y')? true : false;
				
				if(deal)
				{
					// default to trading ajax handler
					var ref	   = 'Invest';
					var imgRef = 'trade-med';
					var locn   = 'ajax-deal';

					// go to record directly using sedol
					$(deal_img).attr({      'id'    : 'img_' + val['sedol'],
								'src'	: 'http://www.hl.co.uk/__data/assets/image/0016/22723/invest.gif',
								'alt'	: ref,
								'title' : 'Invest now in ' + val['title'],
								'class'	: 'spacer-left-half'
									 });
				}
				else
				{
					// Add different attributes to the image if you cannot trade online in this stock
					$(deal_img).attr({                'src'		: 'http://qa.hl.co.uk/__data/assets/image/0008/5453576/grey-arrow.png',
									  'alt'		: 'Not tradeable online',
									  'title'	: 'This security is not tradeable online',
									  'class'	: 'spacer-left-half'
									 });
									  
					$(deal_img).css('cursor', 'default');
				}
			}

			// Add to virtual portfolio option
			if(action == 'add')
			{
				vp_img = $(document.createElement('img'));

				$(vp_img).attr({'src'	: '/img/icons/virtual-portfolio.gif',
								'alt'	: 'Add to virtual portfolio',
								'title' : 'Add to virtual portfolio',
								'class'	: 'spacer-left-half' });
			}

			var can_deal = deal ? cell_link(index, 'identifier', val['sedol'], deal_img, '', 'deal', type) : deal_img;

			// Add the stock details to the row, creating links for each element
			$(row).children('td:first').html(cell_link(index, 'identifier', val['sedol'], identifier, 'block', '', type));
			$(row).children('td:nth-child(2)').html(cell_link(index, 'identifier', val['sedol'], title, 'block', '', type));
			$(row).children('td:last').html(cell_link(index, 'identifier', val['sedol'], chart_img, '', 'chart', type));
			$(row).children('td:last').append(can_deal);

			if(action == 'add')
				$(row).children('td:last').append(cell_link(index, 'identifier', val['sedol'], vp_img, '', 'virtual_portfolio', type));

			// Append the row to our results table
			$(results_table_id + " tbody:first").append(row);
		});

		// Clear the pagination row cells
		$(pagination_row).children('td:first').html('');
		$(pagination_row).children('td:nth-child(2)').html('');
		$(pagination_row).children('td:last').html('');

		$(results_table_id + " " + pagination_row_top).addClass('box-hide');

		// Do we need to show any pagination at all?
		if(num_results > search_limit)
		{
			// Create pagination variables
			var next_offset		= parseInt($(offset_field).val()) + search_limit;
			var previous		= '';
			var next		= '';
			var pages_container     = '';
			var pages		= Math.ceil(num_results/search_limit);
			var curr_page		= parseInt($(offset_field).val()) / search_limit;

			// Do we need a previous button
			if(next_offset > search_limit)
			{
				var previous_offset = parseInt($(offset_field).val()) - search_limit;
				previous = $(document.createElement('a'));

				$(previous).attr({ 'class'	: 'link-headline',
								   'href'	: '#',
								   'title'	: 'Previous' })
						   .text('Previous')
						   .click(function(){
								pagination_pages(this);
								return false;
							});
			}

			// Do we need a next button
			if(num_results > search_limit && next_offset < num_results)
			{
				var next = $(document.createElement('a'));
				$(next).attr({ 'class'	: 'link-headline',
							   'href'	: '#',
							   'title'	: 'Next' })
					   .text('Next')
					   .click(function(){
							pagination_pages(this);
							return false;
						});
			}
	
			// Do we need to display any pages
			if(pages > 0)
			{
				// Create a container for the pages links
				pages_container = $(document.createElement('div'));

				$(pages_container).text('Page: ');

				// Create a link for all but the page we are on
				for (var i=1; i <= pages; i++)
				{
					var page_link = '';
					if(i != (curr_page + 1))
					{
						page_link = $(document.createElement('a'));
						
						$(page_link).attr({ 'class'	: 'link-headline',
								   'href'	: '#',
								   'title'	: i })
						   .text(i)
						   .click(function(){
								pagination_pages(this);
								return false;
							});

						$(pages_container).append(page_link);
					}
					else
					// If we are on this page just create some text within a strong tab
					{
						var page_link = $(document.createElement('strong'));

						$(page_link).text(i);
					}

					// Add the page link followed by a space
					$(pages_container).append(page_link);
					$(pages_container).append(' ');
				}
			}

			// Add the pagination links to the various rows in the table
			$(pagination_row).children('td:first').html(previous);
			$(pagination_row).children('td:nth-child(2)').html(pages_container);
			$(pagination_row).children('td:last').html(next);

			$(results_table_id + " " + pagination_row_top).removeClass('box-hide');

			// Clone the pagination, including the event handling to display it at the bottom as well
			var pagination_bottom = $(results_table_id + " " + pagination_row_top).clone(true);
			$(pagination_bottom).attr('id', 'pagination-row-bottom');

			// Append the pagination to the bottom of the table
			$(results_table_id + " tbody:first").append(pagination_bottom);

		}
		else
		{
			$("tr#pagination-row").hide();
		}
	}
	
	// Remove the box-hide class from the stock search table and the key, or increase the opacity to 1
	if(num_results > 0)
	{
		$(key_id + ", " + results_table_id).removeClass('box-hide');
		$(key_id + ", " + results_table_id).css({'opacity' : '1'}).fadeIn('fast');
	}
	else
	{
		// Hide the table
		$(key_id + ", " + results_table_id).addClass('box-hide').css({'opacity' : '0'});
	}

	// Hide the loading image
	$(loading_img).addClass('box-hide');
}

function getActionRef(f, ref){
	return (ref_type = f.action.value)? ref_type : ref;
}

function remove_child_nodes(e){
	//if (e.hasChildNodes()) while (e.childNodes.length >= 1) e.removeChild(e.firstChild);
	e.innerHTML='';
}

// embolden search words
function highlight_words(txt)
{
	var search_wds = search_val.split(' ');

	var reg = "";

	for(var word in search_wds)
	{	
		if(search_wds[word].length >= char_min)
		{
			reg += "("+search_wds[word]+")|";
		}
	}

	reg = reg.substr(0,reg.length-1);

	var txt_re = new RegExp(reg, 'gi');

	return txt.replace(txt_re, function (term){ return '<strong style="color:#50954C;">' + term + '</strong>'; });
}

// set boxes visibility - only one box can be visible at any given time
var list_count=2;

function display_box(status, index){

	if(status == true && index != -1){
		// re-run search - only required when multiple search instances are being used
		search_val   = '';
		search_index = index;
		if( !stock_search(getElement(data_ids[search_index])) && (e = getElement(list_id+list_tps[search_index])) ){
			remove_child_nodes(e);
			e.style.display = 'none';
		}
	}else{
		var i, e;
		var checked_search = check_search();
		for(i=0; i<=list_count; i++){
			if(list_id && (e = getElement(list_id + i)) != false){
				if( i == list_tps[search_index] && status == true && checked_search == true){
					e.style.display = 'block';
					e.style.zIndex = '10';
					e_focus = true;
				}else{
					e.style.display = 'none';
					if(data_ids.length > 1) remove_child_nodes(e);
				}
			}
		}
	}
}

// handle ajax response, if valid display results
function ajax_handle_stock_search(rs)
{
	var stock_list = (!rs || typeof(rs) == 'object' || rs == "") ? rs : eval('(' + rs + ')' );

	if(stock_list != false){
	
		var stock_val = stock_list['stocks'];
		var pid = stock_list['meta']['pid'];

		if( (ele = document.getElementById('cache_used')) )
		{
			ele.innerHTML = ( stock_list['meta']['cache_found']==true ? 'Yes' : 'No' );
		}
		if( (ele = document.getElementById('elapsed')) )
		{
			ele.innerHTML = stock_list['meta']['elapsed'];
		}

                // Should we be displaying results in a popup box or as part of the page
		if(results_box)
		{
			display_results_box( ((stock_val.length > 0)? stock_val : 2), stock_list['meta']['num_results'] );
		}
		else
		{
			display_results_page( ( (stock_val.length > 0)? stock_val : 2), stock_list['meta']['num_results'] );
		}

		ajax_queue_stock.close_process(pid, stock_list);		
		stock_no = -1;
	}
}

function complete_search(data){
	ajax_handle_stock_search(data);
}

// Fires stock search based on pagination clicks
function pagination_pages(page,stock_suggestion_disabled )
{
	var link	= $(page).text();
	var curr_offset = parseInt($(offset_field).val());
	//var curr_offset = parseInt(getUrlParam('offset'));
	var offset;

	switch(link)
	{
		case 'Next':
			offset = curr_offset + search_limit;
		break;

		case 'Previous':
			offset = curr_offset - search_limit;
		break;

		default:
			var page_num	= parseInt(link);
			var offset		= (page_num - 1) * search_limit;
		break;
	}

	$(offset_field).val(offset);
	if( !stock_suggestion_disabled )
	{
		stock_search(document.getElementById('stock_search_input'));
	}
	else
	{
		var curr_offset = parseInt(getUrlParam('offset'));
		var offset;

		switch(link)
		{
			case 'Next':
				offset = curr_offset + search_limit;
			break;

			case 'Previous':
				offset = curr_offset - search_limit;
			break;

			default:
				var page_num	= parseInt(link);
				var offset		= (page_num - 1) * search_limit;
			break;
		}

		$(offset_field).val(offset);
		document.forms["stock_search"].submit();
	}
}

// Create a link to various locations from the stock table
function cell_link (id, prefix, sedol, contents, display, loc, type)
{
	// Create the variables required
	var new_link	= $(document.createElement('a'));
	var new_id		= prefix + '_' + sedol + '_' + id;
	var href		= '';

	// Switch the location we want to send users to
	switch(loc)
	{
		case 'deal':
			href = deal_link + '?sedol=';
		break;

		case 'virtual_portfolio':
			href = vp_link + '?action=add&sedol=';
		break;
		
		case 'chart':
		default:
                        if(type == 5)
                        {
                                href = fund_chart_link + '?title=' + stock_title + '&sedol=';
                        }
                        else
                        {
                        	href = chart_link + '/';
                        }
		break;
	}

	// Create the link tag
	$(new_link).attr({ 'id'		: new_id,
					   'class'	: (display == 'block') ? 'link-hidden' : '',
					   'href'	: href + sedol})
			   .css({ 'display' : display })
			   .append(contents);

	// Return the newly created link
	return new_link;
}

// capture all key press and key up events
document.onkeypress = capture_keypress;
document.onkeyup = capture_keyup;
document.onclick = capture_id;


