/*
 *
 * File: basicQuery.js
 *
 * Javascript for Verity K2 Enterprise Web Sample Templates - Basic Query
 *
 * Depends upon:
 *      none
 */

var g_blnLastChecked = false;

// Should the search query be checked for VQL and single/double quotes?
// If yes and the query contains some, THESAURUS, TYPO and SOUNDEX are NOT applied.
var g_blnCheckDisableTST = true;

// Helper function to trim whitespace
String.prototype.trim = function()
{
  var strThis = this;
  strThis = strThis.replace(/^\s*(.*)/, "$1");
  strThis = strThis.replace(/(.*?)\s*$/, "$1");
  return strThis;
}

Array.prototype.isset = function(key)
{
    for (i in this)
    {
        if (key == i) return true;
    }
    return false;
}
    
/*
 * =====================================================================
 *                 F O R M   S U B M I T   &   C L E A R
 * =====================================================================
 */
 
function generateQuery(form, g_strTypo, g_strSoundex, g_strThesaurus)
{
    var strTextInput = getValue(form, "TextInput");
    strTextInput = strTextInput.trim();
    
    // backward compatibility: check if TextInput is available as field at
    // all, if not, try to read-out QueryText
    if (strTextInput == "")
    {
        strTextInput = getValue(form, "QueryText");
    }
    
    // encode any non-ASCII chars into utf-8 charcodes and send them
    // over the wire as {XXX}
    strTextInput = encodeUtf8Entities(strTextInput);

    setValue(form, "QueryText", strTextInput);
    setValue(form, "hiddenOriginalQueryText", strTextInput);
    setValue(form, "hiddenBasicQueryText", strTextInput);

    var strSourceQuery = "";
	// exclude pdf
	// -----------
    var strExcludePDF = getExcludePDF(form);
    if (strExcludePDF != "")
    {
        strSourceQuery = "(" + strExcludePDF + ")";
    }

    var TSTenabled = (g_strTypo || g_strSoundex || g_strThesaurus) &&
					 g_blnCheckDisableTST &&
   		             expandQueryWithTST(strQueryText);

	// typo, soundex, thesaurus
	// ------------------------
	var strTSTResult = "";

    if (strTextInput != "" && TSTenabled) {
	    var arrQueryTextSplitted = strTextInput.split(" ");
	    var boolMode = " <OR> ";
	    var sSkippedWords = "";

		for (var i=0; i < arrQueryTextSplitted.length; ++i) {
			var sWord = arrQueryTextSplitted[i];
			var sWordLower = sWord.toLowerCase();
		    var bIsBool = false;
		    
			if (sWordLower == "und" || sWordLower == "and" || sWordLower == "+") {
				boolMode = " <AND> ";
				bIsBool = true;
			}
			if (sWordLower == "oder" || sWordLower == "or") {
				boolMode = " <OR> ";
				bIsBool = true;
			}
			if (sWordLower == "nicht" || sWordLower == "not" || sWordLower == "-") {
				boolMode = " <NOT> ";
				bIsBool = true;
			}
			if (sWord != "" && !bIsBool) {
				if (sWord.indexOf("<") != 0) {
					if (sWord.indexOf("-") == 0) {
						sWord = sWord.substr(1);
						boolMode = " <NOT> ";
						bIsBool = true;
					}
					if (sWord.indexOf("+") == 0) {
						sWord = sWord.substr(1);
						boolMode = " <AND> ";
						bIsBool = true;
					}
					if (g_strTypo) {
					    if (strTSTResult != "") {
					        strTSTResult = strTSTResult + boolMode;
					    }
   					    // inkludiere das evtl. falsch geschriebene Wort ebenfalls
					    // da wenn es richtig ist, Verity weniger findet als wenn
					    // kein Typo angeschaltet wurde...
				        strTSTResult = strTSTResult + "(" + sWord + ",<TYPO/1>" + sWord + ")";
				    }
					if (g_strSoundex) {
					    if (strTSTResult != "") {
					        strTSTResult = strTSTResult + boolMode;
					    }
			        	strTSTResult = strTSTResult + "(<SOUNDEX>" + sWord + ")";
					}
					if (g_strThesaurus) {
					    if (strTSTResult != "") {
					        strTSTResult = strTSTResult + boolMode;
					    }
				        strTSTResult = strTSTResult + "(<THESAURUS>" + sWord + ")";
					}
				} else {
					sSkippedWords += sWord + " ";
				}
				
				// set mode for next word
				boolMode = " <OR> ";
			}
		}
		
		sSkippedWords.trim();
		
		if (strTSTResult != "") {
			if (strSourceQuery == "") {
				strSourceQuery = strTSTResult;
			}
			else {
				strSourceQuery += " <AND> (" +strTSTResult+ ")";
			}
		}
		
		// Delete IQP Query, since for e.g. <typo/n> queries any
		// _wrongly_ typed word delivers 0 results.
		// Set any skipped words instead there.
		setValue(form, "QueryText", sSkippedWords);
	}

    setValue(form, "SourceQueryText", strSourceQuery);

	// disable the submit button, so if the search takes a little longer the user does
	// not do click-click-click
	// the search field with the name "search" may not exist if the form is the header 
	// search form
	if (form.elements['search'])
	{
		form.elements['search'].disabled = true;
	}
	
    // finally: submit
    // -----------------------
    form.submit();
}


/*
 * =====================================================================
 *                 H E L P E R   F U N C T I O N S
 * =====================================================================
 */

// checks if a string contains Verity Search VQL
// or strings in single or double quotes. These
// things are pretty much screwy up the above code
function expandQueryWithTST(str)
{	
	// at first find any single or double quote
	if (str.match(/[\'\"]/)) return false;

	// now find any VQL inside by matching <something> tags
	if (str.match(/\<.+?\>/)) return false;
	
	// this seems to be a normal string...
	return true;
}

function getValue(myForm, name) {
    if (myForm == null) return "";
	myElem = myForm.elements[name];
	if (myElem == null) return "";
	return myElem.value;
}

function setValue(myForm, name, value) {
	if (myForm == null) return false;
	myElem = myForm.elements[name];
	if (myElem == null) return false;
	myElem.value = value;
	return true;
}

function getExcludePDF(form)
{
    var strResult = "";
    var elmExcludePDF = form.elements["ExcludePDF"];
    if (elmExcludePDF)
    {
        var strExcludePDF = elmExcludePDF.checked;
        if (strExcludePDF == true) {
            strResult = "<NOT> MIME-Type <MATCHES> application/pdf";
        }
    }

    return strResult;
}

//
// inspired by from http://aktuell.de.selfhtml.org/artikel/javascript/utf8b64/utf8.htm
//
function encodeUtf8Entities(source)
{
     source = source.replace(/\r\n/g,"\n");
     var dest = "";
     
     for (var n=0; n<source.length; n++)
     {
         var c=source.charCodeAt(n);
         if (c<128)
         {
             dest += String.fromCharCode(c);
         }
         else if(c>127)
         {
             dest += "{"+c+"}";
         }
     }
     return dest;
}

//
// Calls generateQuery for the head search field.
//
function generateQueryHead() {
    
	var form = document.getElementById("formBasicQueryHead");
	if (!form || typeof form != "object")
	{
		alert("Cannot find form, please ensure that\nit has the unique ID \"formBasicQueryHead\".");
		return false;
	}
	
    generateQuery(form, false, false, false);   
}
