// This is the JavaScript for the title search page.  It is used by the Comics realm
// and by other non-comics realms.
//
// These functions depend on the existance of the following JavaScript variables
// defined in an external script source (usually htdocs/script/data/search_comics.js
// or equivalent for other realms.
//
//  var search_realm (e.g. comics)
//  var search_title_data (array of...)
//      "created_flag|title_key|issue_code|page_num|title_issue_name|category|section|search_words"
//
// Also, this depends on the existance of two specific HTML objects in the containing
// form.
//
//  TABLE (element id=results_table)
//  INPUT (forms[0].search_title)
//
// Note that in the data source, you must ensure that none of the | separated fields
// are empty, since IE's RE matching is crap, and it discards empty fields.
//

// You can put this as an onLoad function if you want and we will check for ?ParameterSearch
// on page load and auto-populate the search results.
function autoSearch() {
    form = document.forms[0];

    // See if we have a query arg, and init the name.
    url = document.URL;
    if (url.indexOf ('?') > 0) {
        query = unescape (url.substring(url.indexOf('?')+1, url.length));
        if (query != '') {
            form.search_title.value = query;
            findTitles ();
        }
    }
}

// This is the function which does the findTitles.  It should be the "onClick" for a
// button on the page near the SEARCH_TITLE text field.
function findTitles() {
    var search_string = new String (document.forms[0].search_title.value);

    // Trim search string, then split into lower case words
    search_string = search_string.toLowerCase();
    search_string = search_string.replace (/^[^a-z0-9]+/, "");
    search_string = search_string.replace (/[^a-z0-9]+$/, "");

    if (search_string == '') {
        return;
    }

    // List up all the words we're going to try and match.
    var re1 = /[^a-z0-9]+/;
    var words = search_string.split (re1);

    // Clear the "found issue/title" table rows.
    var tbl = document.getElementById('results_table');
    while (tbl.rows.length > 1) {
        tbl.deleteRow(1);
    }

    // Check each title/issue, and see if we can match all words.
    var title_match = 0;
    var last_matched_title_key = "";

    for (var i = 0; i<search_title_data.length; i++) {

        // Get all the fields for this title/issue
        var re2 = /\|/;
        var fields = search_title_data[i].split (re2);

        var word_match = 0;
        for (var j = 0; j<words.length; j++) {
            if ( fields[7].indexOf (words[j]) >= 0) {
                word_match++;
            }
        }

        // Did we match all words?
        if (word_match == words.length) {

            // Get the title_key first, this may suffice.
            var title_key = fields[1];

            // If we already matched the entire title, then don't both matching any
            // single issues inside the title, that's just confusing.
            if (title_key == last_matched_title_key) {
                continue;
            }

            // Get the rest of the info.
            var created_flag = fields[0];
            var issue_code = fields[2];         // "." if no code, i.e. match entire title.
            var page_num = fields[3];
            var title_issue_name = fields[4];
            var category = fields[5];
            var section = fields[6];

            // We're going to create a row now, we're just arguing details.
            var lastRow = tbl.rows.length;
            var row = tbl.insertRow(lastRow);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);
            var cell4 = row.insertCell(3);

            if (title_match < 20) {
                cell1.appendChild(document.createTextNode(category));
                cell2.appendChild(document.createTextNode(section));

                // If the title/issue exists in the DB then we link to it.
                if (created_flag != 0) {
                    var link = document.createElement('a');

                    // Sometimes we've matched a title (Code = ".")
                    if (issue_code == ".") {
                        link.setAttribute('href', '/' + search_realm + '/title/' + title_key + '.html');
                        last_matched_title_key = title_key;

                    // Sometimes a specific issue within a title.
                    } else if (page_num == 1) {
                        link.setAttribute('href', '/' + search_realm + '/title/' + title_key + '.html#' + issue_code);

                    } else {
                        link.setAttribute('href', '/' + search_realm + '/title/' + title_key + '-' + page_num + '.html#' + issue_code);
                    }
                    link.appendChild(document.createTextNode(title_issue_name));
                    cell3.appendChild(link);
                } else {
                    cell3.appendChild(document.createTextNode(title_issue_name));
                }

                var link = document.createElement('a');
                link.setAttribute('href', 'http://dev.spiderfan.org/edit/title_detail.html#title_key=' + title_key);
                link.appendChild(document.createTextNode('Edit'));
                cell4.appendChild(link);

            } else {
                cell1.appendChild(document.createTextNode('...'));
                cell2.appendChild(document.createTextNode('...'));
                cell3.appendChild(document.createTextNode('Too many titles, refine your search...'));
                cell4.appendChild(document.createTextNode('...'));
                break;
            }
            title_match++;
        }
    }

    if ( title_match == 0 ) {
        document.forms[0].count.value = "No";
        document.getElementById ('results_div').style.display = 'none';
    } else {
        document.forms[0].count.value = title_match;
        document.getElementById ('results_div').style.display = 'block';
    }
}
