/* - ++resource++custom_jq.js - */
/* Custom jQuery scripts for Prettig personeel */

/* Updates the link of the 'Start gratis' tab so it redirects
   to the registration page, not the page that describes advantages
   of registration*/
change_register_link = function() {
    tab_id = '#portaltab-start-gratis'

    link = jq(tab_id + ' a');
    link.attr('href', portal_url + '/join_form/');

    /* We check if we are on the join_form page, in this case we
       set the tab as 'selected'*/
    url = window.location.href;
    if (url.match('join_form')) {
	jq('#hrm-globalnav .selected').addClass('plain');
	jq('#hrm-globalnav .selected').removeClass('selected');
	jq(tab_id).addClass('selected');
    }
};

/* Worklocation livesearch */
wl_livesearch = function(event) {
    if (event.keyCode == '38' || event.keyCode == '40' || event.keyCode == '13') {
	/* User hit key up/down/enter */
	return;
    }

    url = 'wl_livesearch?' + jq('#worklocations_livesearch_form').serialize();
    results_id = '#worklocation_livesearch_results'

    jq(results_id).load(url, function() {
	    /* If there is only one link, this one becomes active.*/
	    links = jq(results_id + ' a');
	    if (links.length == 1) {
		links.addClass('active');
		return;
	    }
	    
	    /* If there is no active link, the first one becomes active. */
	    if (jq(results_id + ' a.active').length == 0) {
		jq(results_id + ' a:first').addClass('active');
	    }
	});

};

/* Allows to navigate with keyboard in the livesearch results. */
wl_livesearch_navigation = function(event) {
    active = jq('#worklocation_livesearch_results a.active')

    if (event.keyCode == '13') {
	/* User hits 'return' */
	event.preventDefault();

	/* We find the active link and go to the worklocation */
	if (typeof(active.attr('href')) == 'string') {
	    window.location = active.attr('href');
	}
    }
    else if (event.keyCode == '38') {
	/* User hits 'key up' */
	new_active = active.parent().prev().find('a:first');
    }
    else if (event.keyCode == '40') {
	/* User hits 'key down' */
	new_active = active.parent().next().find('a:first');
    }
    else {
	new_active = '';
    }

    if (new_active.length > 0) {
	active.removeClass('active');
	new_active.addClass('active');
    }
};


jq(document).ready(function() {
    change_register_link();
    jq('#worklocation_livesearch').keyup(wl_livesearch);
    jq('#worklocation_livesearch').keydown(wl_livesearch_navigation);
});

