/*
 *
 * File: advancedQuery.js
 *
 *  Javascript for Verity K2 Enterprise Web Sample Templates - Advanced Query Generation
 *
 *  This code combines the form entry fields using VQL operators. If this is changed
 *  to use a different query parsing syntax then the Search module will need to be modified
 *  as well to change the setSourceParser() argument (currently set to "Simple").
 *
 * Depends upon:
 *      forms.js
 */



// Helper function to trim whitespace
String.prototype.trim = function()
{
  var strThis = this;
  strThis = strThis.replace(/^\s*(.*)/, "$1");
  strThis = strThis.replace(/(.*?)\s*$/, "$1");
  return strThis;
}


/*
 * =====================================================================
 *                 F O R M   S U B M I T   &   C L E A R
 * =====================================================================
 */
function generateQueryAdvanced(form, g_strTypo, g_strSoundex, g_strThesaurus)
{
    var strOrigQueryText = getValue(form, "QueryText");
    
    strOrigQueryText = encodeUtf8Entities(strOrigQueryText);
    
	//remember original query field for later
    setValue(form, "hiddenOriginalQueryText", strOrigQueryText);
    // the basic query field may not contain advanced fields since if the user
	// returns to the advanced form these are doubled!
    setValue(form, "hiddenBasicQueryText", strOrigQueryText);

    //
    // Generate the IQP style query part
    //
    var strNewQueryArr = new Array();
    strNewQueryArr[strNewQueryArr.length] = getAll(form);
    strNewQueryArr[strNewQueryArr.length] = getExact(form);
    strNewQueryArr[strNewQueryArr.length] = getAtLeastOne(form);
    strNewQueryArr[strNewQueryArr.length] = getNone(form);
	
	// all features into normal search field
	// -------------------------------------
	var sBooleanQueryText = "";
    for (var i = 0; i < strNewQueryArr.length; i++) {
        if (strNewQueryArr[i] == "") continue;
        
        // add padding if this is not the first element
        if (sBooleanQueryText != "") {
	        sBooleanQueryText += " AND ";
	    }
        sBooleanQueryText += "(" + strNewQueryArr[i] + ")";
    }
    
    // SNde298: nicht nur der Text im unteren Formularfelder,
    // auch die Texte für "alle", "keines", ... müssen encoded werden
    sBooleanQueryText = encodeUtf8Entities(sBooleanQueryText);
    
   	// set the original query plus the IQP part
    setValue(form, "QueryText", strOrigQueryText + " " + sBooleanQueryText); 

	// Generate the source query part (VQL)
	var strSourceQuery = "";
	// exclude PDF, lang, Author, Title, DC_description into advanced field
	// -----------------------
    var strExcludePDF = getExcludePDF(form);
    if (strExcludePDF != "")
    {
        strSourceQuery += "(" + strExcludePDF + ")";
    }

    var strAuthor = getValue(form, "Author");
    strAuthor = strAuthor.trim();
    if ( strAuthor != "" ) {
        if (strSourceQuery != "") {
            strSourceQuery += " AND ";
        }
		// SNde340: besteht der Autor-Suchbegriff aus mehreren Worten,
		// wird nur nach dem letzten im Autor gesucht; nach den anderen im Text.
		// deshalb muss geklammert werden 
        //strSourceQuery += "(" + strAuthor + ":AUTHOR)";
        strSourceQuery += "((" + strAuthor + "):AUTHOR)";
    }

    var strTitle = getValue(form, "Title");
    strTitle = strTitle.trim();
    if ( strTitle != "" ) {
        if (strSourceQuery != "") {
            strSourceQuery += " AND ";
        }
		// SNde340: besteht der title-Suchbegriff aus mehreren Worten,
		// wird nur nach dem letzten im title gesucht; nach den anderen im Text.
		// deshalb muss geklammert werden 
        //strSourceQuery += "(" + strTitle + ":DRETITLE)";
        strSourceQuery += "((" + strTitle + "):DRETITLE)";
    }

	// AUTO87, SNde340: besteht der Description-Suchbegriff aus mehreren Worten,
	// wird nur nach dem letzten in der description gesucht; nach den anderen im Text.
	// deshalb muss geklammert werden 
    var strDcDescription = getValue(form, "DC_Description");
    strDcDescription = strDcDescription.trim();
    if ( strDcDescription != "" ) {
        if (strSourceQuery != "") {
            strSourceQuery += " AND ";
        }
        //strSourceQuery += "(" + strDcDescription + ":DC.DESCRIPTION)";
        strSourceQuery += "((" + strDcDescription + "):DC.DESCRIPTION)";
    }

	// set the VQL query part
    setValue(form, "SourceQueryText", strSourceQuery);
	
	// disable the submit button, so if the search takes 
	// a little longer the user doesn't click to often
	form.elements['search'].disabled = true;
	form.elements['reset'].disabled = true;
	
	// finally: submit
	// -----------------------
    form.submit();
}


function clearAdvancedFormFields(form)
{
    var strFormFieldArr = new Array("All", "Exact", "AtLeastOne", "None",
                                    "Title", "Author", "DC_Description",
                                    "StartDate", "EndDate", "QueryText", 
                                    "hiddenOriginalQueryText", "hiddenBasicQueryText"
                                    );

    for (var i = 0; i < strFormFieldArr.length; i++) {
        setValue(form, strFormFieldArr[i], "");
    }
    
    setSelect(form.elements["collections"], "");
    setSelect(form.elements["VLang"], "all");
    form.elements["ExcludePDF"].checked = false;        
}

/*
 * =====================================================================
 *                 H E L P E R   F U N C T I O N S
 * =====================================================================
 */
 
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;
}

/*
 * =====================================================================
 *                 I N P U T   F I E L D S  ->  V Q L
 * =====================================================================
 */

// wandelt den Inhalt des Feldes "Alle Suchbegriffe finden" in eine boolsche Abfrage mit "AND" um
// "xx AND yy"
function getAll(form)
{
    var strResult = getValue(form, "All");
    strResult = strResult.trim();
    if ( strResult != "" ) {
        //strResult = "+" + strResult.replace(/\s+/g, " +");
        strResult = strResult.replace(/\s+/g, " AND ");
    }
    return strResult;
}

//wandelt den Inhalt des Feldes "Alle Suchbegriffe finden" in eine boolsche Abfrage mit Hochkomma um
// "xx yy"
function getExact(form)
{
    var strResult = getValue(form, "Exact");
    if ( strResult != "" )
    {
        //strResult = '+"' + strResult + '"';
        strResult = '"' + strResult + '"';
    }
    return strResult;
}

// mindestens ein Wort -> mit Leerzeichen trennen 
//"xx yy"
function getAtLeastOne(form)
{
    var strResult = getValue(form, "AtLeastOne");
    strResult = strResult.trim();
    if ( strResult != "" ) {
        //strResult = strResult.replace(/\s+/g, ", ");
        strResult = strResult.replace(/\s+/g, " ");
    }
    return strResult;
}

//keines der WÃ¶rter
// "NOT (xx yy)"
function getNone(form)
{
    var strResult = getValue(form, "None");
    strResult = strResult.trim();
    if ( strResult != "" ) {
        //strResult = " " + strResult;
        //strResult = strResult.replace(/\s+/g, " -");
        strResult = "NOT(" + strResult.replace(/\s+/g, " ")+ ")";
    }
    return strResult;
}



function getDate(form, strStartOrEnd)
{
    var strResult = getValue(form, strStartOrEnd + "Date");
    strResult = strResult.trim();
    if ( strResult != "" ) {
        if ( strStartOrEnd == "Start" ) {
            strResult = "Date >= " + strResult;
        }
        else if ( strStartOrEnd == "End" ) {
            strResult = "Date <= " + strResult;
        }
        else {
            strResult = "the argument to the javascript function getDate must be a string that equals either 'Start' or 'End'";
        }
    }
    return strResult;
}

function getMimeType(form)
{
    var strResult = "";
    var elmMimeType = form.elements["MimeType"];
    if (elmMimeType) {
        var strMimeType = elmMimeType.value;
        switch (strMimeType) {
            case "application/pdf":
            case "text/html":
            case "text/xml":
                strResult = "MIME-Type <MATCHES> " + strMimeType;
                break;
            case "ms-excel":
            case "ms-powerpoint":
            case "msword":
            case "plain":
                strResult = "MIME-Type <CONTAINS> " + strMimeType;
                break;
            case "wordperfect":
                strResult = "MIME-Type <SUBSTRING> " + strMimeType;
                break;
            // For ALL and unknown, let it default to empty string.
            case "all":
            default:
                break;
        }
    }
    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;
}

// ACI: Abfrage des (Index-)Feldes "FILETYPE"
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";
            strResult = "NOT (.pdf:FILETYPE)";
        }
    }
    return strResult;
}

function getVLang(form)
{
    var strResult = "";
    var strLang = getValue(form, "VLang");
    strLang = strLang.trim();
        
    if ( strLang != "" &&  strLang != "all") {
        strResult = "VLang=\"" + strLang + "\"";
    }
    return strResult;
}
