/* -- Rich search, Hogeschool Rotterdam
@author : Danny de Zeeuw

/* with categories, and keyboard support
--------------------------------------- */

/* -- Search JSON object*/
//var hrSearchJson;

/* -- Search configuration */
var hrSearchConfig = {
    startSearchChar: 3,
    searchHighlight: 0,
    javascriptSearch: 1,
    searchInjection: 0
}

var error =0;

$(document).ready(function () {
    hrSearchInit();
});


/* -- Search init*/
function hrSearchInit(arg) {

    if (hrSearchConfig.javascriptSearch) hrSearchJavascriptSearch();

    $('.close').click(function (e) {
        $(this).parent().fadeOut();
        return false;
    });

    $.ajaxSetup({
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(errorThrown);
        }
    });
    
    
}

function hrSearchHighlight(arg) {
    var arr = arg.split(' ');
    for (var i = 0; i < arr.length; i++) {
        var a = arr[i].toLowerCase();
        $.each($('#hrSearchResults a'), function () {
            var Content = $(this).html().split(' ');
            var Str = '';
            for (var i = 0; i < Content.length; i++) {
                var c = Content[i].toLowerCase();
                if (c == a) {
                    Str += '<span class="hrSearchHighlight">' + Content[i] + '</span> ';
                } else {
                    Str += Content[i] + " ";
                }
            }
            $(this).html(Str);
        });
    }
};

function hrSearchJavascriptSearch() {

    $('#hrSearchInput').keyup(function (event) {
        var code = (event.keyCode ? event.keyCode : event.which);
        if (code == 40) {
            var el = $('#hrSearchResults ul > li:first-child > .items li:first-child');
            el.find('a').focus();
            el.addClass('hover');
            initKeyPressSearch();
            e.preventDefault();
            return false;
        } else if ($(this).val().length >= hrSearchConfig.startSearchChar) {
            hrSearchGetJson($(this).val())
        } else {
            $('#hrSearchResults').fadeOut();
        }
    }).keydown(function (event) {
        var code = (event.keyCode ? event.keyCode : event.which);
        if (code == 13) {
            location.href = "/meta-navigatie/zoekresultaten/?term=" + encodeURIComponent($(this).val());
            event.preventDefault();
        }
    });

}

/* -- get jSon Data*/

function hrSearchGetJson(term) {

    $.getJSON('/handlers/search.ashx/?action=quicksearch&term=' + term, function (data) { hrSearchProcessObject(data); });
}

/* -- Reading and rendering the JSON to a search overview */
function hrSearchProcessObject(data) {
    var container = $('#hrSearchResults ul');
    var content = '' //'<h3>Er zijn geen zoekresultaten gevonden.</h3>';
    container.empty();
    
    var error = 0;
    
    if(data.Categories.length)content = '';
    
    error = (data.Categories.length == 0) ? 1 : 0;
    
    $.each(data.Categories, function (i, cat) {
        content += '<li class="category"><h3>' + cat.Name + '</h3><ul class="items">';
        $.each(cat.Items, function (i, item) {
            content += ' <li><a href="' + item.Link + '" >' + item.Title + '</a></li>';
        });
        content += '</ul></li>';
    });
    
    
    if(error == 0){
        container.append(content);
    	if (hrSearchConfig.searchHighlight) hrSearchHighlight($('#hrSearchInput').val());
    	$('#hrSearchResults').fadeIn();
    }else{$('#hrSearchResults').fadeOut()}
}

// Register keypress events on the rendered results
function initKeyPressSearch() {
    $.each($('#hrSearchResults .items li a'), function () {
        $(this).keydown(function (e) {
            switch (e.keyCode) {
                case 38:
                    navigate($(this), 'up');
                    e.preventDefault();
                    return false;
                    break;
                case 40:
                    navigate($(this), 'down');
                    e.preventDefault();
                    return false;
                    break;
                case 13:
                    window.location = $(this).find('a').attr('href');
                    break;
            }
        });
    })
}

function navigate(el, act) {
    el = el.parent();

    if (act == "down") {
        if (el.next().is('*')) {
            nel = el.next() //next element
        } else if (el.parent().parent().next().is('*')) {
            nel = el.parent().parent().next().find('.items li:first-child'); //next category
        } else { 
            return;
        }
    } else {
        nel = el.prev();
        if (el.prev().is('*')) {
            nel = el.prev() //previous element
        } else if (el.parent().parent().prev().is('*')) {
            nel = el.parent().parent().prev().find('.items li:last-child'); //previous category
        }else{
            $('#hrSearchInput').focus()
            el.removeClass('hover');
            return;
        }
    }
    
    if (nel.is('*')) {
        nel.find('a').focus();
        nel.addClass('hover');
        el.removeClass('hover');
    }
}


/*		
		// Add data to let the hover know which index they have
		for(var i = 0; i < $('#hrSearchResults .items li ').size(); i++) {
			$("#hrSearchResults .items li").eq(i).data("number", i);
		}
		
		// Simulote the "hover" effect with the mouse
		$("#hrSearchResults .items li").hover(
			function () {
				currentSelection = $(this).data("number");
				setSelected(currentSelection);
			}, function() {
				$("#hrSearchResults .items li").removeClass("hover");
				currentUrl = '';
		});


function navigate(direction) {
	// Check if any of the menu items is selected
	if($("#hrSearchResults .items li.hover").size() == 0) {
		currentSelection = -1;
	}
	
	if(direction == 'up' && currentSelection != -1) {
		if(currentSelection != 0) {
			currentSelection--;
		}
	} else if (direction == 'down') {
		if(currentSelection != $("#hrSearchResults .items li").size() -1) {
			currentSelection++;
		}
	}
	setSelected(currentSelection);
}

function setSelected(menuitem) {
	$("#hrSearchResults .items li ").removeClass("hover");
	$("#hrSearchResults .items li ").eq(menuitem).addClass("hover");
	currentUrl = $("#hrSearchResults .items li").eq(menuitem).find('a').attr("href");
}
*/
