/*
beschreibung

*/

function searchBar(mapRef, title, igsUri) {

	this.map=mapRef;
/*
        this.top="";
        this.left="";
        this.width = "";
        this.height = "";
*/
        this.gsquery="raroute";
        this.title= title;
        this.startup = -1;
        this.http_request = false;
        this.xmlhttp =false;
        this.igsUri = igsUri;
//        this.messagebox = messagebox;
//        this.igsUri = "/igs/radwege2.igs";
        this.CategorieQuery = "";
        this.ListQuery = "";
        this.result = new Ext.Window( {
                  id:  'routeInfoResult', 
                  title    : 'Routendetails',
                  width    : 600,
                  height   : 400,
                  y    : 160,
                  collapsible: true,
                  expandOnShow : true,
                  layout      : 'fit',
                  html: '<div id="result">Hier stehen die Ergebnisse</div>',
                  plain       : true,
                  animCollapse: true,
                  autoScroll : true,
                  expandOnShow: true,
                  closeAction :'hide'
                });

        this.downloadPic="/radwege/icon_gps.gif";
        this.writeDOM = function ( left, top, width, height, oStyle)	{
             this.top = top;
             this.left = left;
             this.width = width;
             this.height = height; 
             var formheight=260 ;
             var listypos = this.top + formheight;
             var listsize =this.height - formheight +22; 
             var detailsize = this.height - this.map.height -2;         
             getLayer("Search").reference=this;
             getLayer("SearchList").style.overflow="auto";
             getLayer("SearchList").innerHTML='<font size="2"><p style="margin-top: 0; margin-bottom: 0">&nbsp;</p>An dieser Stelle erhalten Sie die Resultate der Suchanfrage. <p style="margin-top: 0; margin-bottom: 0">&nbsp;</p> Für  Routenvorschläge w&auml;hlen Sie die gew&uuml;nschten Auswahlkriterien und dr&uuml;cken Sie auf den Button "suchen"</font>';
             hideLayer ("SearchDetailPrint");
//             getLayer("SearchDetail").style.overflow="auto";
             var query = this.igsUri + '?REQUEST=GETCATEGORY';
             this.xmlhttpcategorie = new ajaxRequest(this, query,
                     function () {  WaitForCategories(getLayer("Search").reference) }
                        );
             this.xmlhttpcategorie.doRequest();
      }
}

//
//  private functions
//


function WaitForCategories (obRef) {
//
// Event handler for xmlhttp-Request 
// calls a function when load of document is done
//

        if (obRef.xmlhttpcategorie.req.readyState == 4) {
            if (obRef.xmlhttpcategorie.req.status == 200) {
                  obRef.XmlCategories=StringToXML(obRef.xmlhttpcategorie.req.responseText, "text/xml");
                  BuildCategorieForm(obRef);
            } else {
                alert('Bei dem Request ist ein Problem aufgetreten.');
            }
        }
}

function BuildCategorieForm (obRef) {
//
// builds the form the user can make a selection
// assumes, the xml DOM-Tree is there
//

    var queryroot = obRef.XmlCategories.documentElement;
    var queryitem = queryroot.childNodes;
    var content="";
    content += '<form name="searchform" > ';
    content += '<fieldset> ';
    content += '<legend>' + obRef.title+ '</legend>';
    var numberOfOptions=0;
    var depth = 1;
    for ( var i=0; i<queryitem.length;i++) {
        if (queryitem[i].nodeType != 1 ) continue;  // fuer Gecko Browser 
        var name = queryitem[i].getAttribute("name") ;
        var dbattr = queryitem[i].getAttribute("db") ;
//        content+='<div>';
        content += '<fieldset style="border: 0 solid; padding:4 ;" > ';
        content+='<legend>' + name +'</legend>';
        content += '<select name="' + dbattr +'" size="'+depth+'" onchange="ClearAll(getLayer(' +"'"+"Search'"+').reference)">'; 

        var option = "alle";
        content+='<option  value="'+option+'">'+'- - - - - beliebig - - - - -'+'</option>';

        var values = queryitem[i].childNodes;
        for (var k=0; k<values.length; k++) {
          if (values[k].nodeType != 1 ) continue;
          var optioname = values[k].getAttribute("name");
          var option = values[k].firstChild.nodeValue ;
          content+='<option  value="'+option+'">'+optioname.replace(/_/g," ")+'</option>';
        }
       content+= '</select>';
       content += '</fieldset> ';
//       content+='</div>';
       numberOfOptions++;
    }
   content+='<div>';
   button ='<button TYPE=BUTTON  style="margin-left: 70px;" onClick="javascript:buildQuery(this.form, getLayer(' +"'"+"Search'"+').reference);">suchen</button>';
   content+= button;
   content+='</div>';
   content += '</fieldset>';
   content+= '</form>';
//   alert(content);
   try {
     getLayer("Search").innerHTML=content;
   }
   catch (exc) { alert (exc);}

}

function buildQuery (aForm, obRef) {
//
// reads the user options from a form, builds Uri for query
// and opens an xmlhttp-request
//

  getLayer("SearchList").innerHTML='<font size="2"><p style="margin-top: 0; margin-bottom: 0">&nbsp;</p>Anfrage wird bearbeitet  ..</font>';
   var query = obRef.igsUri + '?REQUEST=GETLIST' ;
   var queryorder = 1;
   for (i=0;i<aForm.length-1; i++) {
       if (!aForm[i].name ) continue;
       var name=aForm[i].name;
       var value = aForm[i].options[aForm[i].selectedIndex].value
//       alert('name ' + name +'wert ' + value);
       if (value !="alle" && name !="suchen") {
         query += '&QUERY_ATTR' +queryorder+'='+name+'&QUERY_VAL'+queryorder+'='+ unescape("%27")+value+ unescape("%27");
         queryorder = queryorder + 1;
       }  
   }
//   alert (query)
    try {
    obRef.xmlhttplist = new ajaxRequest(obRef, query,
                 function () {  WaitForList(obRef) } );
    obRef.xmlhttplist.doRequest();
    }
    catch(exp) {alert(exp)} 
}

function WaitForList (obRef) {
//
// event handler for  xmlhttp-request, waits for load of doc
// and calls the next function
//

        if (obRef.xmlhttplist.req.readyState == 4) {
            if (obRef.xmlhttplist.req.status == 200) {
                  obRef.xmlList=StringToXML(obRef.xmlhttplist.req.responseText, "text/xml");
                  WriteWegeList(obRef);
            } else {
                alert('Bei dem Request ist ein Problem aufgetreten.');
            }
        }
}

function WriteWegeList (obRef) {
//
// builds a table with the object list,
// updates the div-container 

    var root = obRef.xmlList.documentElement;
    var item = root.childNodes;
    var j=0;
    var content = '<table border="1" cellspacing="0" width="96%" >'

    content += '<tr>';
//    content += '<th BGCOLOR="#C0C0C0" ><font color=#ffffff>' + 'Nr' + '</font></th>';
    content += '<th width="55%" BGCOLOR="#C0C0C0" >Rad- oder Bike-Route</th>';
    content += '</tr>';
    for ( var i=0; i<item.length;i++) {
        if (item[i].nodeType != 1 ) continue;  // fuer Gecko Browser 
        if (item[i].getElementsByTagName("ID").length < 1 ) continue
        var id = item[i].getElementsByTagName("ID")[0].firstChild.nodeValue ;
        var name = item[i].getElementsByTagName("NAME")[0].firstChild.nodeValue ;  
        content += '<tr style="padding:2px" >';
//        content += '<th  style=" vertical-align:top; padding: 2px ">' + id + '</th>';
        content += '<td style="padding-left:4px" width="55%"><a onMouseOver="this.style.color=\'blue\'" onMouseOut="this.style.color=' + unescape("%27")+'black'+unescape("%27")+'" href="javascript:showDetails(getLayer(' +"'"+"Search'"+').reference,\''+id+'\');">' + name + '</a></td>';
        content += '</tr>';
        j++
    }
    content += '<CAPTION>Anzahl gefundene Datens&auml;tze:' + j + '</CAPTION>';
     content += '</table>';
//     content2 = '<span ><font size="1" style="HorizontalAlign:right" >Anzahl Treffer: ' + j + '</span></font>';
//
// Hier noch testen den Text zu optimieren
//
     getLayer("SearchList").innerHTML="";
//     getLayer("SearchList").innerHTML +=content2;
     if (j > 0 ) {
         getLayer("SearchList").innerHTML +=content; 
    } else { 
      getLayer("SearchList").innerHTML='<span ><p style="margin-top: 0; margin-bottom: 0">&nbsp;</p><font size="2" >keine Datens&auml;tze gefunden, &auml;ndern Sie die Suchkriterien</span></font>';
    }

}
function showDetails (obRef, aId) {
//
// builds a table with details of an object
// and updates the div-container
//
    var root = obRef.xmlList.documentElement;
    var item = root.childNodes;
    var imagename="";
    var inletname = "";
    var inlet = "";
    var downloadUri="";
    for ( var i=0; i<item.length;i++) {
        if (item[i].nodeType != 1 ) continue;  // fuer Gecko Browser 
        var id = item[i].getElementsByTagName("ID")[0].firstChild.nodeValue ;
        if ( id == aId ) {
             var weg=item[i].childNodes;
//             alert (weg.length);
             var screencontent = '<table border="0" class="routedetail">' ;
             var printcontent = '<table border="0" >' ;
             var myID = "";
             for (var j=0; j<weg.length;j++) {
                 if (weg[j].nodeType != 1 ) continue; 
                 if ( weg[j].nodeName !="X1" && weg[j].nodeName !="X2" && weg[j].nodeName !="Y1" && weg[j].nodeName !="Y2" && weg[j].nodeName !="DOWNLOAD" ) {
                   var attrname = weg[j].getAttribute("name");
                   var attrvalue = weg[j].firstChild.nodeValue;
                   if (attrname == "Profil" ) { 
                       imagename=attrvalue;
                   }
                   else if ( attrname == "Routen-Nummer" ) {
                       myID = attrvalue;
                   }
                   else if (attrname == "INLET" ) { 
                        inletname=attrvalue ;
                        var profimg ='<img align="left" src="' + imagename + '" hspace="5" height="190" >';
                        var mycontent ='';
                        if (inletname != "_" ) {
                              var inlet='<img align="left" src="' + inletname + '" height="120" >';
                        } 
                        else { 
                              var inlet="";
                        }
                        var legende ='<img align="left" src="/radwege/legende.gif" width="128px" >';
                        mycontent += '<tr>';
                        mycontent += '<th align="left" width="120" >' + 'Piktogramm' + '</th>';
                        mycontent += '<td align="left" >' + inlet + profimg + legende + '</th>'; 
                        mycontent += '</tr>';
//                       screencontent += mycontent;       
                        printcontent += mycontent;       

                   }
                   else if (attrname == "Beschreibung") {
                          var mycontent ='';
                          mycontent += '<tr>';
                          mycontent += '<th align="left" width="120" >' + 'Beschreibung' + '</th>';
                          mycontent += '<td>';
                          var pico ='/radwege/report.gif';
                          var link = '<a href="javascript:showBeschreibung(getLayer(' +"'"+"Search'"+').reference,\''+myID+'\');">'  + '<img align="left" src="' + pico + '" alt="Beschreibung anzeigen"  ></a>';
                          mycontent += link + '</td>';
                          mycontent += '</tr>';
                          var myprintcontent='';
                          myprintcontent += '<tr>';
                          myprintcontent += '<th align="left" width="120" >' + attrname + '</th>';
                          myprintcontent += '<td align="left" >' + attrvalue + '</th>'; 
                          myprintcontent += '</tr>';
                          screencontent += mycontent;       
                          printcontent += myprintcontent;   
              
                   }
                   else {
                     var mycontent ='';
                     mycontent += '<tr>';
                     mycontent += '<th align="left" width="120" >' + attrname.replace(/_/g," ") + '</th>';
                     mycontent += '<td align="left" >' + attrvalue.replace(/_/g," ") + '</th>'; 
                     mycontent += '</tr>';
                     screencontent += mycontent;       
                     printcontent += mycontent;   

                   }
                 } 
                 else if (weg[j].nodeName == "DOWNLOAD" ) {
                     downloadUri  = weg[j].firstChild.nodeValue
                     downloadname = weg[j].getAttribute("name");
                 }
             }
             if (imagename != "_" ) {
                    var pico ='/radwege/profil.gif';
                    var profile='<a href="'+ imagename + '" target="_blank"><img align="left" src="' + pico + '" alt="Profil anzeigen"  ></a>';
                    screencontent += '<tr>';
                    screencontent += '<th align="left" width="120" >' + 'Streckenprofil' + '</th>';
                    screencontent += '<td align="left" >' + profile + '</th>'; 
                    screencontent += '</tr>';
             }

             if (downloadUri != "" ) {
                  screencontent += '<tr>';
                  screencontent += '<th align="left" >' + downloadname + '</th>';
                  screencontent +='<td> <a href="'+ downloadUri + '" target="_blank"><img align="left" src="' + obRef.downloadPic + '" alt="Start Download" ></a></td>';
                  screencontent += '</tr>';
             }
             screencontent += '</table>'; 
             printcontent += '</table>'; 
             var button='';            
             button += '<form id="resetChoice" style="margin-left: 230px;">';
             button +='<button  TYPE=BUTTON onClick="javascript:resetChoice(getLayer(' +"'"+"Search'"+').reference);">Auswahl aufheben</button>';
             button += '</form>';
             var outertable='<table><tr><td width="95%" >';
             outertable+=screencontent;
//             alert(content);
             outertable+='</td>';
             var image='<a href="'+ imagename + '" target="_blank"><img align="right" src="' + imagename + '" alt="vergr&ouml;ssern"  width="120" ></a>';
             if (inlet != "" ) {
                  outertable+='<td align="center" valgin="middle" style="padding-right:20px">'+inlet+'</td>';
             }
             else {
                  outertable+='<td style="vertical-align:top;" >'+' ' +'</td>';
             }
             outertable+='</tr></table>';
             outertable += button;
//             alert(outertable);
//             getLayer("SearchDetail").innerHTML=outertable;
//             getLayer("SearchDetail").innerHTML=screencontent + button;
             getLayer("SearchDetailPrint").innerHTML=printcontent ;
             var x1 = item[i].getElementsByTagName("X1")[0].firstChild.nodeValue ;
             var y1 = item[i].getElementsByTagName("Y1")[0].firstChild.nodeValue ;
             var x2 = item[i].getElementsByTagName("X2")[0].firstChild.nodeValue ;
             var y2 = item[i].getElementsByTagName("Y2")[0].firstChild.nodeValue ;
        }  
    }
    var centerx = (eval(x1)+eval(x2))/2;
    var centery = (eval(y1)+eval(y2))/2;
    var deltax=eval(x2)-eval(x1); 
    var deltay=eval(y2)-eval(y1); 
    var ratio = obRef.map.getSize().w/obRef.map.getSize().h;

    if (deltax/ratio > deltay) { deltay = deltax/ratio;   } 
    else {  deltax =deltay*ratio   }

    x1= centerx - deltax*0.5;
    x2= centerx + deltax*(0.5);
    y1= centery - deltay*0.5;
    y2= centery + deltay*(0.5);
    var offsetx = deltax*0.1;
    var offsety = deltax*0.1;

   var qstring = "&query=" + obRef.gsquery + "&ID=" + aId;

//    var qstring = "&query=route&ID=" + aId;
   obRef.map.layers[1].setQuerString (qstring);
//   obRef.map.layers[1].setQuerString (qstring);
//   obRef.map.layers[2].setQuerString (qstring);


//   alert (obRef.map.layers[0].highlight);
//   obRef.map.updateBBox(x1-offsetx,y1-offsety,x2+offsetx,y2+offsety);
   obRef.map.zoomToExtent(new OpenLayers.Bounds(x1-offsetx,y1-offsety,x2+offsetx,y2+offsety));
//   obRef.messagebox.show();
   obRef.result.show();
   Ext.getCmp('routeInfoResult').body.dom.innerHTML = outertable;


}


function showBeschreibung (obRef, aId) {
                          
   printBeschr = window.open("/geoportal/print/print_rawe.html","printDetails","dependent=yes,scrollbars=yes,status=yes,resizable=yes,location=no,toolbar=yes,menubar=yes,width=780,height=1000");
   printBeschr.focus();

}



function resetChoice(obRef) {

/*    obRef.map.layers[0].highlight = "";
    obRef.map.refresh();
    getLayer("SearchDetail").innerHTML="";
    getLayer("SearchDetailPrint").innerHTML="";
*/
    obRef.map.layers[1].clearQuerString();
//    obRef.map.layers[1].clearQuerString();
//    obRef.map.layers[2].clearQuerString();

    obRef.map.setCenter (obRef.map.getCenter(),obRef.map.getZoom());
    obRef.map.layers[1].redraw();
//    obRef.map.layers[1].redraw();
//    obRef.map.layers[2].redraw();

//    getLayer("SearchDetail").innerHTML="keine Route ausgew&auml;hlt";

    Ext.getCmp('routeInfoResult').body.dom.innerHTML ="keine Route ausgew&auml;hlt";

    getLayer("SearchDetailPrint").innerHTML="";



//    obRef.messagebox.hide();
//    obRef.messagebox.reset();
    obRef.result.hide();
}

function ClearAll (obRef) {

/*    obRef.map.layers[0].highlight = "";

    getLayer("SearchList").innerHTML="";
    getLayer("SearchDetail").innerHTML="";
    getLayer("SearchDetailPrint").innerHTML="";

*/
    obRef.map.layers[1].clearQuerString();
//    obRef.map.layers[1].clearQuerString();
//    obRef.map.layers[2].clearQuerString();
    getLayer("SearchList").innerHTML="";
//    Ext.getCmp('routeInfoResult').body.dom.innerHTML ="keine Route ausgew&auml;hlt";
    getLayer("SearchDetailPrint").innerHTML="";


}

function StringToXML(string) {
// takes a string and converts it to an xml-doc
  if (document.implementation && document.implementation.createDocument) {
     var xmlparser = new DOMParser();
    return xmlparser.parseFromString(string, "text/xml");
  } else if (window.ActiveXObject) {
    var xmldoc = new ActiveXObject("microsoft.xmldom");
    xmldoc.async = "false";
    var status = xmldoc.loadXML(string);   
    if (status) {
      return xmldoc;
      }
    else {
      return null;    
    }
  }
  return null;
}
