﻿/* -------------------
   File: media/js/voc.js
   Author: Eric Fehse
   ------------------- */

var txt_search;
var output;
var results;
var background;
var message;
var txt_cache = "";
var ac_list;
var show_table_headers;

$(document).ready( function() { 
    txt_search = $("input#search");
    ac_list = $("ul#autocomplete");
    output = $("div#word_table");
    results = $("table#results");
    background = $("table#results");
    message = $("span#message");
    
    info_pane = $("#info").add("#stats"); 

    show_table_headers = $("#home").length;

    entry_sv = $('textarea#id_entry_sv');
    entry_de = $('textarea#id_entry_de');

    txt_search.focus().select();
    entry_sv.focus(); // override txt_search, if present...
    

    $("#home button#do_search").click( function() {
        get_results(1);
        return false;
    });

    $("#edit button#do_search").click (function() {
        get_results(1, 100);
        return false;
    })

    $("#home button#reset_search").click (function() {
        txt_search.val('');
        return false;
    })

    $("#edit button#reset_search").click (function() {
        txt_search.val('');
        get_results(1, 100);
        return false;
    })

    // hide autocomplete list if the page is clicked somewhere
    $("body").click( function() {
        ac_list.hide();
    });
    // process key presses in the search field
	txt_search.keypress(function(e) {
		var char = e.which;
		var key_code = e.keyCode;
        if (char == 13)
		{
			get_results(1);
			return false;
		}
		else if (key_code==38)
		{
            ac_cursor_press("up");
            return false;
		}
        else if (key_code==40)
		{
            ac_cursor_press("down");
            return false;
		}
		else
		{
            // allow a timeout for the the character to be added to the textbox
            window.setTimeout('post_autocomplete()', 5);
		}
	});
	// colorize the tables, if present...
	colorize_tables();

	// special chars on home page
	$('#options a').click( function() {
	    txt_search.val(txt_search.val() + $(this).html());
	    txt_search.focus();
	    return false;
	});

	// Edit page
    // add event listeners to special characters on edit page
    // clicking on the character adds it at cursor position to the text area

    $entry_sv = $('#id_entry_sv');
    $entry_de = $('#id_entry_de');
    $search_home = $('#home #search'); // home only!
    $('#special_chars a.sv').click( function() {
        append_and_focus($entry_sv, $(this).html());
        return false;
    });
    $('#special_chars a.de').click( function() {
        append_and_focus($entry_de, $(this).html());
        return false;
    });

    // add event listeners for adding tags from the tag list
    var $tag_input = $('#id_tags');
    $('ul#tag_list a').click( function() {
        var space = ' ';
        if ($tag_input.val().length == 0)
            space = '';
        $tag_input.val($tag_input.val() + space + $(this).html());
        $tag_input.focus();
        return false;
    });
});

function append_and_focus(elem, text) {
    elem.val(elem.val() + text);
    elem.focus();
}

function colorize_tables() {
	$("table#results tr:odd").css("background-color", "#ddd");
    $("table.analyze tr:odd").css("background-color", "#ddd");
    $("#stats table tr:odd").css("background-color", "#ddd");
    //$("#multi_edit table tr:odd").css("background-color", "#ddd");
}

function post_autocomplete() {
    var search_term = txt_search.val();
    if (search_term == txt_cache)
        return;
    txt_cache = search_term;
    if (search_term.length > 1) // start only after at least two characters
    {
        var post_data = {'search_term': search_term};
        $.post('/autocomplete/', post_data, display_autocomplete);
    }
    else
    {
        ac_list.hide();
    }
}

function get_results(page, size) {
    var search_term;
    // check if there is a selected item in the autocomplete list.
    // if so, look up the text of the selected item
    li_sel = $("ul#autocomplete > li.sel");
    if (li_sel.length == 1)
    {
        search_term = li_sel.text();
        txt_search.val(search_term);
    }
    // otherwise look up the current text in the search field
    else
    {
        search_term = txt_search.val();
    }
    txt_cache = search_term; // this will stop older autocomplete requests from being displayed
    var voc_search = $('#voc_search')[0].checked;
    var tag_search = $('#tag_search')[0].checked;
    var post_data;
    post_data = {'search_term': search_term, 'page': page,
                 'show_table_headers': show_table_headers,
                 'size': size, 'voc_search': voc_search, 'tag_search': tag_search
                 };
    $.post('/lookup/', post_data, display_results);
    results.hide();
    info_pane.hide("normal");
    message.show();
}

function display_results(response_data) {
    output.html(response_data).show();
    $("#footer").removeClass("start");
    results.show();
    message.hide();
    ac_list.hide();
    $("table#results tr:odd").css("background-color", "#ddd");
    txt_search.focus().select();
    // adjust footer position
    $("#footer").css("margin-top", 565 - $("table#results").height());
}

function display_autocomplete(response_data) {
    if (response_data == "none")
    {
        ac_list.hide();
    }
    else
    {
        /* Extract the search term from the beginning of the html.
           Display the outocomplete list only if it is the most recent search term. */
        pos = response_data.indexOf("$");
        term = response_data.substring(0,pos);
        if (term == txt_cache)
        {
            html = response_data.slice(pos+1);
            ac_list.html(html).show();
        }
    }
}

function ac_cursor_press(direction) {
    if(ac_list.filter(":visible").length > 0)
    {
        if (direction=="up")
        {
            if ($("ul#autocomplete > li.sel").length == 0)
                $("ul#autocomplete > li:last").addClass("sel");
            else
                $("ul#autocomplete > li.sel").removeClass("sel").prev().addClass("sel");
        }
        else
        {
            if ($("ul#autocomplete > li.sel").length == 0)
                $("ul#autocomplete > li:first").addClass("sel");
            else
                $("ul#autocomplete > li.sel").removeClass("sel").next().addClass("sel");
        }
    }
}

function delete_card(card_id, element) {
    var post_data = {'card_id': card_id};
    $.post('/delete/', post_data, confirm_delete);
}

function confirm_delete(response_data) {
    var tr_selector = "tr#" + response_data;
    $(tr_selector).fadeOut("normal", colorize_tables);
}

function toggle_favorite(element, card_id) {
    $(element).removeClass().addClass('favorite-wait');
    var post_data = {'card_id': card_id};
    $.post('/toggle_favorite/', post_data, toggle_return);
}

function toggle_return(response, status) {
    result = eval('(' + response + ')');
    anchor = $(result.id);
    anchor.removeClass().addClass(result.fav_class);
    anchor.attr('title', result.fav_title);
}


