//$HeadURL: svn+ssh://jwilden@svn.wald.intevation.org/deegree/apps/igeoportal-standard/branches/2.5_testing/modules/csw/csw_functions_search.js $
/*----------------------------------------------------------------------------
 This file is part of deegree, http://deegree.org/
 Copyright (C) 2001-2009 by:
 - Department of Geography, University of Bonn -
 and
 - lat/lon GmbH -

 This library is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free
 Software Foundation; either version 2.1 of the License, or (at your option)
 any later version.
 This library is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 details.
 You should have received a copy of the GNU Lesser General Public License
 along with this library; if not, write to the Free Software Foundation, Inc.,
 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

 Contact information:

 lat/lon GmbH
 Aennchenstr. 19, 53177 Bonn
 Germany
 http://lat-lon.de/

 Department of Geography, University of Bonn
 Prof. Dr. Klaus Greve
 Postfach 1147, 53001 Bonn
 Germany
 http://www.geographie.uni-bonn.de/deegree/

 e-mail: info@deegree.org
----------------------------------------------------------------------------*/
// counter for selected thesaurus keywords
var k = 0;

// send data for simple search
function performSimpleSearch() {
	var searchme = document.mainform.terms.value;
	
	//var isDataset = document.mainform.resourceType[0].checked;
    //var isCollection = document.mainform.resourceType[1].checked;
    //var resourceType = null;
    //For 2.0..0
    /*if ( isDataset ) {
        resourceType = 'csw:dataset';
    } else if ( isCollection ) {
        resourceType = 'csw:datasetcollection';
    }*/
    //For 2.0.2
    resourceType = 'gmd:MD_Metadata';
    
	if ( searchme.length < 3 ) {
		alert( 'The search term needs to consist of three or more characters.' );
		document.mainform.terms.focus();			
		document.mainform.terms.value='';
        
	} /*else if ( !isDataset && !isCollection ) {
        alert( "Please choose either 'dataset' or 'data series'." );
        document.mainform.resourceType[0].focus();
        
    }*/ else  {
		var s = "../../control?rpc=<?xml version='1.0' encoding='UTF-8'?>";
		s += "<methodCall>";
		s += "<methodName>cswClient:simpleSearch</methodName>";
		s += "<params>";
        
        //param[0] = catalog name
		s += "<param><value><array><data>";
		s += "<value><string>CATA1</string></value>";
		s += "</data></array></value></param>";
        
		//param[1] = search struct
        s += "<param><value><struct>";
        s += createMember( "RPC_SIMPLESEARCH", searchme, "string" );
        s += createMember( "RPC_FORMAT", "ISO19115", "string");
        s += createMember( "RPC_RESULTTYPE", "RESULTS", "string" );
        s += createMember( "RPC_STARTPOSITION", "1", "string");
        s += createMember( "RPC_TYPENAME", resourceType, "string" );
        s += createMember( "RPC_ELEMENTSETNAME", "brief", "string");
        s += createMember ("RPC_PROTOCOL", "POST", "string");
        s += createMember( "RPC_MDTYPE", "dataset,series,application", "string" );
        // if more params are needed, add them here to this struct!
        
		s += "</struct></value></param>";
		s += "</params>"
		s += "</methodCall>";
	
		document.mainform.action = s;
		document.mainform.submit();
	}
}

// (JM) finds all datasets belonging to a dataseries.
// dataseries-id = dataset-parentId
function performSeriesChildrenSearch( id, catalog ){

    var req = "control?rpc=<?xml version='1.0' encoding='UTF-8'?>";
    req += "<methodCall><methodName>cswClient:childrenSearch</methodName><params>";
    
    //param[0] = catalog name
    req += "<param><value><array><data>";
    req += "<value><string>" + catalog + "</string></value>"; // derzeit nur ein Katalog.
    req += "</data></array></value></param>";
    
    //param[1] = search struct
    req += "<param><value><struct>";
    //s += "<member><name>RPC_SIMPLESEARCH</name><value><string>" + searchme+"</string></value></member>";
    req += "<member><name>RPC_DATASERIES</name><value><string>" + id + "</string></value></member>";
    req += "<member><name>RPC_FORMAT</name><value><string>ISO19115</string></value></member>";
    req += "<member><name>RPC_RESULTTYPE</name><value><string>RESULTS</string></value></member>";
    req += "<member><name>RPC_STARTPOSITION</name><value><string>1</string></value></member>";
    req += "<member><name>RPC_TYPENAME</name><value><string>gmd:MD_Metadata</string></value></member>"; // searching for datasets only
    req += "<member><name>RPC_ELEMENTSETNAME</name><value><string>brief</string></value></member>";
    req += "<member><name>RPC_PROTOCOL</name><value><string>POST</string></value></member>";
    req += "</struct></value></param></params>";
    req += "</methodCall>";
    
    // in the same window as the first list
    dsWindow = window.open( req, "main" );
    dsWindow.parent.focus();
}

// send data for detailled search
function performDetailedSearch() {
    if ( validate() ) {
        /*var s = "../../control?rpc=<?xml version='1.0' encoding='UTF-8'?>";
        s += "<methodCall>";
        s += "<methodName>cswClient:detailedSearch</methodName>";
        s += "<params>" + getRequestParameter() + "</params>";
        s += "</methodCall>";*/

        var s = "../../control?rpc=";
        s += createMethodCall( "cswClient:detailedSearch", getRequestParameter(), "UTF-8" );
        document.searchForm.action = s;
        document.searchForm.submit();
    }
}

// validate input for detailled search
function validate() {
	var s1 = document.searchForm.terms.value;
	var s2 = document.searchForm.TOPICCATEGORY.value.substring(0,3);
	var s4 = document.searchForm.datefromyear.value;
	var s5 = document.searchForm.datefrommonth.value;
	var s6 = document.searchForm.datefromday.value;
	var s7 = document.searchForm.datetoyear.value;
	var s8 = document.searchForm.datetomonth.value;
	var s9 = document.searchForm.datetoday.value;
	// csw 2.0.0
    /*
    var s10 = document.searchForm.resourceType[0].checked;
    var s11 = document.searchForm.resourceType[1].checked;
    */
    var s12 = document.searchForm.datasetChk.checked;
    var s13 = document.searchForm.seriesChk.checked;
    var s15 = document.searchForm.applicationChk.checked;
    
    var error = '';
    
	if ( s1.length < 1 && s2 == '...' && s4.length < 1 && s7.length < 1 
         // && emptyKeywords() 
         ) {
		 error += "Please define at least one search criterion besides the bounding box.\n";
	 }
     if ( s1.length > 0 && s1.length < 3  
         // || shortKeywords() 
         ) {
		 error += "The search term needs to consist of three or more characters.\n";
		 document.searchForm.terms.value = '';
	 }
	 
	 //csw 2.0.0
	 /*if ( !s10 && !s11 ) {
        error += "Please choose either 'dataset' or 'data series'.\n";
     }*/
     
     if ( s4.length > 0 && s4.match(/^\d{4}$/) == null || 
          s7.length > 0 && s7.match(/^\d{4}$/) == null ) {
         error += "Please insert a four digit year.\n";
     }
     if ( s5.length > 0 && s5.match(/^\d{2}$/) == null || 
          s8.length > 0 && s8.match(/^\d{2}$/) == null ) {
         error += "Please insert a two digit month.\n";
     }
     if ( s5.length > 0 && s5 > 12 || s8.length > 0 && s8 > 12 ) {
         error += "Please use a valid value for month( 01 - 12 ).\n";
     }
     if ( s6.length > 0 && s6.match(/^\d{2}$/) == null ||
          s9.length > 0 && s9.match(/^\d{2}$/) == null ) {
         error += "Please insert a two digit day.\n";
     }
     if ( s6.length > 0 && s6 > 31 || s9.length > 0 && s9 > 31 ) {
         error += "Please use a valid value for day.\n";
     }
     
     if ( !s12 && !s13 && !s14 && !s15 ) {
         error += "Please check at least one Metadata type";
     }
     if ( error.length > 0 ) {
         alert (error);
         return false;
     }
	 return true;
}

// keywords for thesaurus
function emptyKeywords(){
    if ( document.searchForm.keywords != null ){
        var s3 = document.searchForm.keywords.value;
        if ( s3.length < 1 ) {
            return true;
        }
        return false;
    }
    return false;    
}

// keywords for thesaurus
function shortKeywords(){
    if ( document.searchForm.keywords != null ){
        var s3 = document.searchForm.keywords.value;
        if ( s3.length < 3 ) {
            return true;
        }
        return false;
    }
    return false;    
}

function getRequestParameter() {
    // all form data is saved into variables
    var searchme = document.searchForm.terms.value;
    var topic = document.searchForm.TOPICCATEGORY.value;
    
    //var isDataset = document.searchForm.resourceType[0].checked;
    //var isCollection = document.searchForm.resourceType[1].checked;
    //var resourceType = 'gmd:MD_Metadata';
    //for 2.0.0
    /*if ( isDataset ) {
        resourceType = 'csw:dataset';
    } else if ( isCollection ) {
        resourceType = 'csw:datasetcollection';
    }*/
    
    var key = '';
	if ( document.searchForm.keywords != null ){
        key = document.searchForm.keywords.value;
    }
    
    var fromyear = document.searchForm.datefromyear.value;
    var frommonth = document.searchForm.datefrommonth.value;
    var fromday = document.searchForm.datefromday.value;
    
    var toyear = document.searchForm.datetoyear.value;
    var tomonth = document.searchForm.datetomonth.value;
    var today = document.searchForm.datetoday.value;
    
    var minx = document.searchForm.minx.value;
    var miny = document.searchForm.miny.value;
    var maxx = document.searchForm.maxx.value;
    var maxy = document.searchForm.maxy.value;
    
    var ignoreArea = 0;
    if ( document.searchForm.ignoreArea != null ) {
        if ( document.searchForm.ignoreArea.checked )  {
            ignoreArea = 1;
        }
    }
    
    // Metadata type
    var mdType = '';
    var resourceType = "gmd:MD_Metadata";
    var datasetChk = document.searchForm.datasetChk.checked;
    var seriesChk = document.searchForm.seriesChk.checked;
    var applicationChk = document.searchForm.applicationChk.checked;
    
    if ( datasetChk ) {
        if ( mdType.length > 0 ) {
            mdType = mdType.concat( ',', 'dataset' );
        } else {
            mdType = 'dataset';
        }
    }
    if ( seriesChk ) {
        if ( mdType.length > 0 ) {
            mdType = mdType.concat( ',', 'series' );
        } else {
            mdType = 'series';
        }
    }
    if ( applicationChk ) {
        if ( mdType.length > 0 ) {
            mdType = mdType.concat( ',', 'application' );
        } else {
            mdType = 'application';
        }
    }
    
    
// #######################################################################
// param[0] = catalog name(s)
    var s = "<param><value><array><data>";
    s += "<value><string>CATA1</string></value>";
    s += "</data></array></value></param>";
    
// #######################################################################
// param[1] = search struct
    s += "<param><value><struct>";
    // data from simple search
    if ( searchme.length > 0 ) {
        s += createMember( "RPC_SIMPLESEARCH", searchme, "string" );
    }
    // data from environment classification
    if ( topic.substring(0,3) != '...' ) {
        s += createMember( "RPC_TOPICCATEGORY", topic, "string" );
    }
    // Keyword to search
    if ( key.length > 0 ) {
        s += createMember( "RPC_KEYWORDS", key, "string" );
    }
    // search from given date till given date
    if ( fromyear.length == 4 )  {
        frommonth = ( frommonth.length < 1 )? "01":frommonth;
        fromday = ( fromday.length < 1 )? "01":fromday;
        
		s += "<member><name>RPC_DATEFROM</name>";
		s += "<value><struct>";
		s += createMember( "RPC_YEAR", fromyear, "string" );
		s += createMember( "RPC_MONTH" , frommonth, "string" );
		s += createMember( "RPC_DAY", fromday, "string" );
		s += "</struct></value>";
        s += "</member>";
    }
    if ( toyear.length == 4 )  {
        tomonth = ( tomonth.length < 1 )? "12":tomonth;
        today = ( today.length < 1 )? "31":today;
        
		s += "<member><name>RPC_DATETO</name>";
		s += "<value><struct>";
		s += createMember("RPC_YEAR", toyear, "string" );
		s += createMember( "RPC_MONTH", tomonth, "string");
		s += createMember( "RPC_DAY", today, "string");
		s += "</struct></value>";
        s += "</member>";
    }

    // Bounding-Box
    if ( !ignoreArea && minx.length > 0 && miny.length > 0 && maxx.length > 0 && maxy.length > 0 )  {
		s += "<member><name>boundingBox</name><value><struct>";
		s += createMember( "minx", minx, "double" );
		s += createMember( "miny", miny, "double" );
		s += createMember( "maxx", maxx, "double" );
		s += createMember( "maxy", maxy, "double" );
		s += "</struct></value></member>";
	}
    
    // format of request/response
    s += createMember( "RPC_FORMAT", "ISO19115", "string" );
    s += createMember( "RPC_RESULTTYPE", "RESULT", "string" );
    s += createMember( "RPC_STARTPOSITION", "1", "string" );
    s += "<member><name>RPC_TYPENAME</name><value><string>"+resourceType+"</string></value></member>";
    s += createMember( "RPC_MDTYPE", mdType, "string" );
    s += createMember( "RPC_ELEMENTSETNAME", "brief", "string" );
    s += createMember( "RPC_PROTOCOL", "POST", "string" );
    // if more params are needed, add them here to this struct!
    
    s += "</struct></value></param>";
    // end of param[1] - NO MORE PARAMS MAY FOLLOW BELOW !!!
    
    return s;
}

/*
// Send a Thesaurus-search
function performThesaurus( ) {
    var thesaurus = document.searchForm.searchterm.value;
    if ( thesaurus.length < 3 ) {
		alert( 'Der Suchbegriff muss mindestens drei Zeichen umfassen' );
		document.searchForm.searchterm.value = '';
    } else {
        var s = "<?xml version='1.0' encoding='UTF-8'?>";
        s = s + "<methodCall>";
        //Der Name des Services ist hier fix.
        s = s + "<methodName>catalogClient:thesaurusSearch</methodName>";
        s = s + "<params><param><value><array><data>";
        //Derzeit nur ein Thesaurus-Katalog.
        s = s + "<value><string>ThesaurusName</string></value>";
        s = s + "</data></array></value></param>";
        s = s + "<param><value><string>"+thesaurus+"</string></value></param>";
        s = s + getRequestParameter();
        s = s + "</params></methodCall>";

        document.searchForm.action = 'cswClient?rpc=' + s ;
        document.searchForm.submit();
    }
}

function takeThesaurusTerm() {
    for( i = 0; i < document.searchForm.THESAURUSTERM.length; i++ ) {
        if ( document.searchForm.THESAURUSTERM.options[i].selected == true ) {
            if ( k > 0 || document.searchForm.keywords.value != '' ) {
                document.searchForm.keywords.value =
                        document.searchForm.keywords.value + ',' + document.searchForm.THESAURUSTERM.options[i].value;
            } else {
                document.searchForm.keywords.value =  document.searchForm.THESAURUSTERM.options[i].value;
                k++;
            }
        }
    }
}
*/

function reset() {
    resetKeywords();
    document.searchForm.terms.value = '';
    if ( document.searchForm.searchterm != null ) {
        document.searchForm.searchterm.value = '';
    }
    document.searchForm.datefromyear.value = '';
    document.searchForm.datefrommonth.value = '';
    document.searchForm.datefromday.value = '';
    document.searchForm.datetoyear.value = '';
    document.searchForm.datetomonth.value = '';
    document.searchForm.datetoday.value = '';
    document.searchForm.minx.value = '';
    document.searchForm.miny.value = '';
    document.searchForm.maxx.value = '';
    document.searchForm.maxy.value = '';
    if ( document.searchForm.geoservice != null ) {
        document.searchForm.geoservice.checked == false;
    }
    if ( document.searchForm.ignoreArea != null ) {
        document.searchForm.ignoreArea.checked == false;
    }
    clearList();
}

function resetKeywords() {
    if ( document.searchForm.keywords != null ) {
        document.searchForm.keywords.value = '';
        k = 0;
    }
}

function clearList() {
    var box = document.forms['searchForm'].TOPICCATEGORY;

    for (var i = 0; i < box.length; i++) {
        box.options[i].selected = false;
    }
    box.options[0].selected = true;
}

// update spacial extend of bbox according to the size of the map in the portal
// if map is changed in portal, user must call function updateAreaValues() by hitting the button, 
// in order to get the min, max of the current bbox into the search fields
function updateAreaValues() {
    var o = parent.myOpener;
    parent.setBoundingBox( o );
    var bbox = parent.myBBox;
    
    var minx = Math.round(bbox.minx);
    var miny = Math.round(bbox.miny);
    var maxx = Math.round(bbox.maxx);
    var maxy = Math.round(bbox.maxy);
    
	document.searchForm.minx.value = minx;
    document.searchForm.miny.value = miny;
    document.searchForm.maxx.value = maxx;
    document.searchForm.maxy.value = maxy;
}
