/**
 * A nice fancy search interface
 */
$(document).ready(function()
{
	$(window).resize(function() {
		positionSearchResults();
	});
	
    var newSearch;
    
    $("div.search input.submit").hide();
	$("div.search input.query").click(function(e) 
	{
		if(newSearch)
			clearTimeout(newSearch);
                
		newSearch = search();
	});
    $("div.search input.query").attr("autocomplete", "off");
    $("div.search 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 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() { $('.search').find('form').removeClass('active'); });
					} 
				}
			});
        }
    );
}

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 input.query");
	$('.search').find('form').addClass('active');	
	productDescriptionItems = 3; // number of product description items 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 {
	
		// format collections results
		if (collectionsArr.length > 0) {
		
			html += "<div class=\"section\"><h1>Collections</h1>";
			$.each(collectionsArr, function(i, item){
				html += "<h2>" + item.title + "</h2><p>" + item.description + "</p><a href=\"" + item.url + "\">more &raquo;</a><br />";
			});
			
			html += "</div>";
		}
		
		// format product results
		if (productArr.length > 0) {
		
			html += "<div class=\"section\"><h1>Products</h1>";
			$.each(productArr, function(i, item){
				
				html += "<div class=\"product\"><h2>" + item.title + "</h2>";
				html += "<a href=\"" + item.url + "\"><img src=\"/media.php?i=" + item.mediaid + "&x=40\" border=\"0\" /></a>";
				
				
				if (item.description) {
					
					html += "<p>" + item.description + "</p>";
					
					/* previously a newline seperated list
					descriptionArr = item.description.split("\r\n", productDescriptionItems);
					
					if (descriptionArr.length > 0) {
						html += "<ul>";
						
						$.each(descriptionArr, function(i, item){
							html += "<li>" + item + "</li>";
						});
						
						html += "</ul>";
					}
					*/
				}

				html += "</div><br style=\"clear: both\">";
			});
			
			html += "</div><br style=\"clear: both\">";
		}
		
		// any results left are content results
		if (json.length - collectionsArr.length - productArr.length != 0) {
		
			html += "<div class=\"section\"><h1>Website</h1>";
			
			$.each(json, function(i, item){
				if (item.type == 'Node') 
					html += "<h2>" + item.title + "</h2><p>" + item.description + "</p><a href=\"" + item.url + "\">more &raquo;</a><br />";
			});
			
			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()
{
	$("div#searchBox").css({"left" : $("form#search").offset().left - 65});
	$("div#searchBox").css({"top" : $("form#search").offset().top - 22});
}

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;
}
