//javascript
window.ajaxCalls = [];
var timeoutVal;
var ajaxCallDelay = 1;

var searchImages = [{'name':'/images/search-bg-begin.png',
						'height':30,
						'width':271},
					{'name':'/images/search-bg-slice.png',
						'height':12,
						'width':271},
					{'name':'/images/search-footer-bg.png',
						'height':30,
						'width':271},
					{'name':'/images/search-list-bg.png',
						'height':61,
						'width':245},
					{'name':'/images/search-list-bg-hover.png',
						'height':61,
						'width':245},
					{'name':'/images/search-section-title-bg.png',
						'height':30,
						'width':271}];


if (document.images)
{
	for(var each in searchImages){
	  pic1= new Image(searchImages[each]['height'],searchImages[each]['width']);
	  pic1.src=searchImages[each]['name'];
	}
}



$(document).ready(function(){
	$('input[name*=keywords]:first').attr('autocomplete', 'off');
	$('input[name*=keywords]:first').keyup(function(){
		if($(this).val() == ''){
			removeSearchList();
		}else{
			clearTimeout(timeoutVal);
			timeoutVal = setTimeout(ajaxSearch, ajaxCallDelay);
		}
	});
	$('input[name*=keywords]:first').blur(function(){
		timeoutVal = setTimeout(hideSearchList, 200);
	});
	$('input[name*=keywords]:first').focus(function(){
		showSearchList();
	});
});

/**
 * Call ajax
 */
function ajaxSearch() {
	
	/* Clear interval everytime */
	clearTimeout(timeoutVal);
	var str = $('input[name*=keywords]').val();
	window.ajaxCalls[window.ajaxCalls.length] = str;

	var pData = '';
	(hasVariable('dev'))? pData = "dev=true&func=searchStr&str="+str: pData = "func=searchStr&str="+str;

	$.ajax({
		type:"POST",
		url: "/modules/search/ajaxSearch.php",
		data: pData,
		dataType:'json',
		success:function(msg){
			var data = this['data'].toString();
			var str = data.substr(data.lastIndexOf('str=', data)+4);
			var lastStr = window.ajaxCalls[window.ajaxCalls.length-1].toString();
			if(lastStr == str){
				addToSearchList(processSearchObj(msg));
			}
		}
	});
}

/**
 * get variable from url
 */
function hasVariable(gvar) {
    
	var url = window.location.href;
	var indexOfVar = url.lastIndexOf(gvar);

	if(indexOfVar != -1){
		//IF variables exists then return true;
		return true;
	}
	return false;
}

function processSearchObj(obj){
	var rObj = [];
	for(var each in obj){
		var sObj = obj[each];
		rObj[rObj.length] = {'sid':sObj['index'],
							 'section':{'id':sObj['table'], 'name':sObj['section_name']},
							 'html':sObj['teaser_html'],
							 'url_fragment':sObj['url_fragment']
							}
	}
	return rObj;
}

function cl(obj) {
	var useConsole = true;
	var useAlert = false;
	if(useConsole && $.browser.mozilla){
		console.log(obj);
	}else if(useAlert){
		alert(obj);
	}
}

/**
 * Revmove search List
 */
function removeSearchList() {
	var con = $('#header-links');
	$(con).find('#search-con').empty();
}

/**
 * hide Search list
 */
function hideSearchList() {
	clearTimeout(timeoutVal);
    var con = $('#header-links');
	$(con).find('#search-con').hide();
}

/**
 * show Search list
 */
function showSearchList() {
    var con = $('#header-links');
	$(con).find('#search-con').show('fast');
}

/**
 * Add to search list
 */
function addToSearchList(obj) {
	/*
	if (window.console && $('input[name*=keywords]').val() == 'checking') {
		console.info("function: addToSearchList");
		console.log("keywords = " + $('input[name*=keywords]').val());
		console.log("obj = " + obj);
	}
	*/
	
	if($('input[name*=keywords]').val() == ''){
		return false;
	}

	var footer_text = '<a href="/search.html?keywords='+encodeURIComponent($('input[name*=keywords]').val())+'">Not in the list? See all results</a>';
	
	/* No Results */
	if(obj.length == 0){
		footer_text = 'No results for <b>"'+encodeURIComponent($('input[name*=keywords]').val())+'"</b> found.';
	}

	/** passed in array of obj [{'sid':'1', 'section':{'id':'personal_banking','name':'Personal_banking'}, 'html':'Title <br/>Lorem <b>ipsum</b> dolor sit amet, cons ectetur adipiscing elit...'}] */
	var con = $('#header-links');
	var width = $(con).css('width');

	//when search-con doesn't exsist add it
	if($(con).find('#search-con').length == 0 || $(con).find('#search-con').children().length == 0){ /*292*/
		var searchConhtml = '<div style="float: right; width: 259px; text-align: left;"><div id="search-con"><div id="search-content"></div><div id="search-footer">'+footer_text+'</div></div></div>';
		$(con).append(searchConhtml);
	}else{
		$(con).find('#search-content').empty();
		$(con).find('#search-footer').html(footer_text);
	}
	
	var i = 0;
	for(var each in obj){
		var section_id = obj[each]['section']['id'];
		var section_name = obj[each]['section']['name'];

		/* this is for special content pages to link to the correct "tab" */
		var url_fragment = obj[each]['url_fragment'];
		
		var sectionClass = 'section';
		if(i==0){
			sectionClass = 'first-section';
		}
		if($(con).find('#search-content #'+section_id).length == 0){
			$(con).find('#search-content').append('<div id="'+section_id+'"><p class="'+sectionClass+'" >'+section_name+'</p></div>');
		}
		
		var table = section_id;
		var index_id = obj[each]['sid'] + "_" + i; // added loop index to ensure uniqueness
		var index = obj[each]['sid'];
		var search_value = encodeURIComponent($('input[name*=keywords]').val());
		var url = '/search.html?commonSearchClick=true&keywords='+search_value+'&table='+table+'&index='+index+'&frag='+url_fragment;
		
		//var listItem = '<p id="'+obj[each]['sid']+'" class="dropshadow"><a href="'+url+'">'+obj[each]['html']+'</a></p>';
		var listItem = '<p id="'+index_id+'" class="dropshadow"><a href="'+url+'">'+obj[each]['html']+'</a></p>';
		/*
		if (window.console && $('input[name*=keywords]').val() == 'checking') {
			console.info("function: addToSearchList");
			console.log("index = " + index);
			console.log("listItem = " + listItem);
			listItem
			console.log(obj[each]);
		}
		*/
		//if($(con).find('#search-content #'+section_id+' #'+obj[each]['sid']).length == 0){
		if($(con).find('#search-content #'+section_id+' #'+index).length == 0){
			$(con).find('#search-content #'+section_id).append(listItem);
		}
		i++;
	}
}

/** $('#header-links p div').remove();
width = $('#header-links p').css('width');
html = '<div style="width:'+width+'; height:200px; position:absolute;"><div id="search-con"><div id="search-content"><p><a href="#">test info</a></p><p><a href="#">test info</a></p></div><div id="search-footer"></div></div></div>';
$('#header-links p').append(html);
*/
