/**
 * A nice fancy search interface
 */
$(document).ready(function(){
	$(window).resize(function() {
		positionSearchResults();
	});	
    var newSearch;    
    $("div.search-bar input.submit").hide();
	$("div.search-bar input.query").click(function(e){
		if (newSearch) {			
			clearTimeout(newSearch);
		}        
		newSearch = search();
	});
    $("div.search-bar input.query").attr("autocomplete", "off");
    $("div.search-bar input.query").keydown(function(e){
        // track last key pressed
        lastKeyPressCode = e.keyCode;		
        switch(e.keyCode)
        {			
            case 38: // up
                break;
                
            case 40: // down
                break;
                
            case 9:  // tab
            case 13: // return
            
				$('form#search').submit();
                break;
                
            default:
                if (newSearch) {
					clearTimeout(newSearch);
				}
                newSearch = setTimeout("search()", 500);
                break;
        }
    });
});

/**
 *  Perform website search
 */
function search(){
    var input = $("div.search-bar input.query");
    var query = input.val();
    if(query == ''){
        return false;
    }    
    input.addClass('activity');    
    // fetch search results
    $.getJSON(
        '/search.php?dataType=json&productResults=3&query=' + query,
        function(json){
			showResults(query, json);			
			$(document).click(function(e) {				
				var target = $(e.target);
				var ancestors = $(target).parents();				
				// if user clicks on any element that isn't a link
				// and the element is not in the search form or box
				// then close the search box
				if (target.type != 'a') {					
					isSearchBoxClick = false;					
					// check if element is inside search form or searchBox dropdown
					ancestors.each(function(i, item){
					if (item.id == "searchBox" || item.id == "search") 
						isSearchBoxClick = true;
					});					
					if (!isSearchBoxClick) {
						$("div#searchBox").slideUp(500);
					}	
				}
		});
     });
}

function findPos(obj){
    var curleft = obj.offsetLeft || 0;
    var curtop  = obj.offsetTop || 0;
    
    while (obj = obj.offsetParent){
        curleft += obj.offsetLeft
        curtop += obj.offsetTop
    }    
    return {x:curleft,y:curtop};
}

/**
 *  Render search data
 */
function showResults(query, json){	
	var input = $("div.search-bar input.query");	
	productDescriptionItems = 4; // number of search results to display
	collectionsArr = getCollectionsFromJSON(json);
	productArr = getProductsFromJSON(json);
	html = '';	
	if (json.length == 0) {
		html += "<div class=\"section\"><h1>Search Results</h1><p>Sorry, no results found</p>";
	}else{	
		if (json.length - collectionsArr.length - productArr.length != 0) {		
			html += "<div class=\"section\"><h1>Website</h1>";			
			var x = 0;
			$.each(json, function(i, item){
				if (x < productDescriptionItems) {
					if (item.type == 'Node') {
						html += "<a class='title' href=\"" + item.url + "\">" + item.title + "</a><p>" + item.description + "</p><a href=\"" + item.url + "\">more &raquo;</a><br />";
						x++;
					}	
				}	
			});			
			html += "</div>";
		}		
		html += "<div class=\"section viewmore\"><a class=\"viewmore\" href=\"/search.php?query=" + query + "\">View all results &raquo;</a></div>";
			
	}
	positionSearchResults();	
	$("div#searchBoxMiddle").html(html);
	$("div#searchBox").slideDown(1000, function() { input.removeClass('activity'); });
}

// positions search results dropdown relative to search form
function positionSearchResults(){
	if(jQuery.browser.msie && jQuery.browser.version < 7){
		// IE6		
		$("div#searchBox").css({"left" : $("form#search > .search-bar-outer > .search-bar").offset().left+30}); 
	}else{
		$("div#searchBox").css({"left" : $("form#search > .search-bar-outer > .search-bar").offset().left+24})
	}	
}

function getCollectionsFromJSON(json){
	var collectionsArr = new Array();	
	$.each(json, function(i, item){		
		if(item.type == 'Collection')
			collectionsArr.push(item);
	});	
	return collectionsArr;
}

function getProductsFromJSON(json){
	var productArr = new Array();	
	$.each(json, function(i, item){		
		if(item.type == 'Product')
			productArr.push(item);
	});	
	return productArr;
}
