/*
 * Copyright 2007 The Australian National University
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this 
 * file except in compliance with the License. You may obtain a copy of the License at 
 *
 *    http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software distributed under 
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
 * KIND, either express or implied. See the License for the specific language governing 
 * permissions and limitations under the License.
 */

/* regular expression used to escape lucene query language control characters in query info input (escapeStrings
 * and escapeStringsNotQuot) */
var escapeRE = new RegExp();
var escapeNotQuotRE = new RegExp();

// checks that query terms do not start with wildcard (checkWildcards)
var wildcardRE = new RegExp();

// removes quotes from around query terms
var quoteRE = new RegExp();

// stores the active box - use by copyThesaurusItem to determine where to copy the item
var activeBox=1;

function submitSimpleQuery(server){	  	
	var textInput = document.getElementById('search_textinput').value.trim();
	if (textInput == "") {
    	return false;
	}
	var queryString = document.getElementById('queryString');
	queryString.value = parseSimpleQuery(textInput,server);  
	return true;
}

function submitSimpleForm(server){	
	var notEmpty = submitSimpleQuery(server);
	if( notEmpty ){
		document.getElementById('thesearchform').submit();
	}
	return false;
}		

function parseSimpleQuery(textInput, server) {
    var queryString = "";    // query info string

    // compile reg expressions used by formatTerms and escapeStrings
    //escapeRE.compile("([\\-\\&\\|!\\(\\)\\{\\}\\[\\]\\^\\\"\\~\\:\\\\\+])", "g");
    escapeRE = /([\-\&\|!\(\)\{\}\[\]\^\"\~\:\\+])/g;
    //quoteRE.compile("^\\\"(.+)\\\"$");
    quoteRE = /^\"(.+)\"$/;
    //wildcardRE.compile("^[\\*\\?]");
    wildcardRE = /^[\*\?]/;
    
    /* "with all the words" box - should be anded together */
    var value = trim(textInput);
    if (value !== "") {
        var words = formatTerms(value.split(/\s+/));  // formatTerms removes quotes around words

        if (! checkWildcards(words)) {
            return "";
        }
        
        queryString = setQueryStringParam(queryString, "queryAnd", escapeStrings(words).join(" "));
    }

    if (queryString == "") {
    	return "";
    } else {
        /* Add name of field to display query */
        var fieldType = "both";      
        queryString = setQueryStringParam(queryString, "queryFieldType", fieldType);
    }  
    
    queryString = setQueryStringParam(queryString, "server", server);   
    
    return queryString;
}


function formatTerms(terms) {
    /* removes quotes from around query terms: terms can be an array of terms or a string - quotes are only
     * removed if present at start and end of the term  - uses quoteRE (defined as global var) */
    if (typeof(terms) == "string") {
        terms = terms.replace(quoteRE, "$1");
    } else {
        for (var i = 0; i < terms.length; i++) {
            terms[i] = new String(terms[i]).replace(quoteRE, "$1");
        }
    }
    
    return terms;
}        

function checkWildcards(strings) {
    // checks that query terms do not start with a ? or * wildcard (wildcards in middle/at end of term are ok)
    var wordFound;
    if (typeof(strings) == "string") {
        if (wildcardRE.test(strings))
            wordFound = strings;
    } else {
        for (var i = 0; i < strings.length; i++) {
            if (wildcardRE.test(strings[i])) {
                wordFound = strings[i];
                break;
            }
        }
    }
    
    if (wordFound != undefined) {
        alert("Query terms cannot start with a ? or * wildcard (term '" + wordFound + "' starts with a wildcard). Wildcards may be included in the middle of query terms or at the end.");
        return false;
    } else {
        return true;
    }
}

function escapeStrings(strings) {
    /* escapes lucene control characters within query terms: terms can be an array of terms or a string - uses
     * escapeRE*/
    if (typeof(strings) == "string") {
        string = strings.replace(escapeRE, "\\$1");
    } else {
        for (var i = 0; i < strings.length; i++) {
            strings[i] = new String(strings[i]).replace(escapeRE, "\\$1");
        }
    }
    
    return strings;
}

function escapeStringsNotQuot(strings) {
    /* escapes lucene control characters other than double quotes within query terms. Used to process phrase 
     * strings, which may contain 1+ phrases delimited by quotes. Terms can be an array of  terms or a 
     * string - uses escapeNotQuotRE */
    if (typeof(strings) == "string") {
        string = strings.replace(escapeNotQuotRE, "\\$1");
    } else {
        for (var i = 0; i < strings.length; i++) {
            strings[i] = new String(strings[i]).replace(escapeNotQuotRE, "\\$1");
        }
    }
    
    return strings;
}        

function checkDate(date) {
    var re = /^(\d{2})[\-\\\/]?(\d{2})[\-\\\/]?(\d{4})/;
    var matches = re.exec(date);
    if (! matches) {
        alert("Error in date entered: date not in \"dd/mm/yyyy\" format");
        return "";
    } else {
        var currentYear = new Date().getFullYear();
        if (matches[3] < 0 || matches[3] > currentYear) {
            alert("Error in date entered: year not between 0000 and " + currentYear);
            return "";
        }
        
        if (matches[2] < 1 || matches[2] > 12) {
            alert("Error in date entered: month not between 01 and 12");
            return "";
        }

        if (matches[1] < 1 || matches[1] > 31) {
            alert("Error in date entered: day not between 01 and 31");
            return "";
        }

        return matches[3] + matches[2] + matches[1];
    }
}

function trim(value) {
    return value.trim();
}

String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};

function setQueryStringParam(queryString, property, value) {
    var re = new RegExp(property + ":\\[.*?[^\\\\]?\\]", "i");
    if (re.test(queryString)) {
        return queryString.replace(re, property + ":[" + value + "]");
    } else if (queryString == "") {
        return property + ":[" + value + "]";
    } else {
        return queryString + " " + property + ":[" + value + "]";
    }
}

function lite(input) {
	input.src = "/images/search_icon_hover.png";
}

function dim(input) {
	input.src = "/images/search_icon.png";
}
