/*
beschreibung

*/

function searchBar(mapRef, title, igsUri) {

	this.map=mapRef;
        this.top="";
/*
        this.left="";
        this.width = "";
        this.height = "";
*/
        this.title= title;
        this.startup = -1;
        this.http_request = false;
        this.xmlhttp =false;
        this.igsUri = igsUri;
//        this.messagebox = messagebox;
//        this.igsUri = "/igs/wanderwege.igs";
        this.CategorieQuery = "";
        this.ListQuery = "";
        this.result = new Ext.Window( {
                  id:  'routeInfoResult', 
                  title    : 'Routendetails',
                  width    : 600,
                  height   : 300,
                  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="/wanderwege/icon_gps.gif";
        this.writeDOM = function ( oStyle)	{
        document.getElementById("Search").reference=this;
        document.getElementById("SearchList").style.overflow="auto";
        document.getElementById("SearchList").innerHTML='<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"';
//        document.getElementById("SearchDetail").style.overflow="auto";
        var query = this.igsUri + '?REQUEST=GETCATEGORY';
        this.xmlhttpcategorie = new ajaxRequest(this, query,
                     function () {  WaitForCategories(document.getElementById("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  class="btn" style="margin-left: 100px;" 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 Get_Total_List (obRef,aID) {
//
// event handler for  xmlhttp-request, waits for load of doc
// and calls the next function
//
       var query = obRef.igsUri + '?REQUEST=GETLIST' ;
       obRef.xmlhttplist = new ajaxRequest(obRef, query,
         function () {
          if (obRef.xmlhttplist.req.readyState == 4) {
            if (obRef.xmlhttplist.req.status == 200) {
                  obRef.xmlList=StringToXML(obRef.xmlhttplist.req.responseText, "text/xml");
                  showDetails(obRef,aID);
            } else {
                alert('Bei dem Request ist ein Problem aufgetreten.');
            }
           }
          }
       );

        obRef.xmlhttplist.doRequest();
}


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="98%" >'

    content += '<tr>';
//    content += '<th BGCOLOR="#C0C0C0" ><font color=#ffffff>' + 'Nr' + '</font></th>';
    content += '<th>' + 'Wanderroute' + '</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 ;  
        var laenge=item[i].getElementsByTagName("LAENGE")[0].firstChild.nodeValue ; 
        var aufstieg =item[i].getElementsByTagName("AUFSTIEG")[0].firstChild.nodeValue ;  
        var abstieg =item[i].getElementsByTagName("ABSTIEG")[0].firstChild.nodeValue ;  

        var time =item[i].getElementsByTagName("TIMETO")[0].firstChild.nodeValue ; 
        var tooltip_options= ',BGCOLOR,' +unescape("%27") +'white' + unescape("%27") +',BORDERCOLOR,' + unescape("%27") + 'black' + unescape("%27");
        content += '<tr>';
//        content += '<th  style=" vertical-align:top; ">' + id + '</th>';
          var temptext=  name + ' ' + ' - L&auml;nge:' + laenge + ' - Wegzeit:' + time;
          temptext += ' - Aufstieg:' + aufstieg + ' - Abstieg:' + abstieg ; 
          
//                                                                                         content += '<td width="55%"><a onMouseOver="this.style.color=' + unescape("%27")+'white'+unescape("%27")+'" onMouseOut="this.style.color=' + unescape("%27")+'black'+unescape("%27")+'" href="javascript:showDetails(getLayer(' +"'"+"Search'"+').reference,\''+id+'\');">' + name + '</a></td>';
        content += '<td width="55%"><a title="' + temptext + '" onMouseOver="this.style.color=\'blue\'"';
/* mit Tip Untip 
        content += 'Tip('+ unescape("%27") + temptext + unescape("%27") + tooltip_options + ')" ';
        content += ' onMouseOut="this.style.color=' + unescape("%27")+'black'+unescape("%27") + ';UnTip()' + '"';
        content+=' href="javascript:showDetails(getLayer(' +"'"+"Search'"+').reference,\''+id+'\');UnTip()">' + name + '</a></td>';
*/
        content += ' onMouseOut="this.style.color=\'black\'"';
//        content+=' href="javascript:showDetails(getLayer(' +"'"+"Search'"+').reference,\''+id+'\')">' + name + '</a></td>';
        content+=' href="javascript:showDetails(getLayer(\'Search\').reference,\''+id+'\')">' + name + '</a></td>';
//        alert(content);
        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>';
    }
/*
    jQuery('#SearchList a').tooltip({
                        showURL: false
                        });
*/

}
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 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 content = '<table border="0" class="routedetail">' ;
             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 {
                     content += '<tr>';
                     content += '<th align="left" width="120" >' + attrname.replace(/_/g," ") + '</th>';
                     content += '<td align="left" >' + attrvalue.replace(/_/g," ") + '</th>'; 
                     content += '</tr>';
                   }
                 } 
                 else if (weg[j].nodeName == "DOWNLOAD" ) {
                     downloadUri  = weg[j].firstChild.nodeValue
                     downloadname = weg[j].getAttribute("name");
                 }
             }
             getLayer("SearchDetailPrint").innerHTML=content +'</table>';
             if (downloadUri != "" ) {
                  content += '<tr>';
                  content += '<th align="left" >' + downloadname + '</th>';
                  content +='<td> <a href="'+ downloadUri + '" target="_blank"><img align="left" src="' + obRef.downloadPic + '" alt="Start Download" ></a></td>';
                  content += '</tr>';
             }
             content += '</table>'; 
             var button='';            
             button += '<form id="resetChoice" style="margin-left: 230px;">';
             button +='<button  TYPE=BUTTON class="btn" onClick="javascript:resetChoice(getLayer(' +"'"+"Search'"+').reference);">Auswahl aufheben</button>';
             button += '</form>';
             var outertable='<table ><tr><td width="65%" >';
             outertable+=content;
//             alert(content);
             outertable+='</td>';
             var image='<a href="'+ imagename + '" target="_blank"><img align="right" src="' + imagename + '" alt="vergr&ouml;ssern"  width="220" ></a>';
             outertable+='<td>'+image+'</td>'
             outertable+='</tr></table>';
             outertable += button;
//             alert(outertable);
//             getLayer("SearchDetail").innerHTML=outertable;
             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.height/obRef.map.width;

    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.05;
    var offsety = deltax*0.05;
//   alert (obRef.map.getNumLayers());
    var qstring = "&query=route&ID=" + aId;
   obRef.map.layers[1].setQuerString (qstring);
   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 resetChoice(obRef) {
    obRef.map.layers[1].clearQuerString();


//    obRef.map.refresh();
    obRef.map.setCenter (obRef.map.getCenter(),obRef.map.getZoom());
    obRef.map.layers[1].redraw();

    Ext.getCmp('routeInfoResult').body.dom.innerHTML ="keine Route ausgew&auml;hlt";

    getLayer("SearchDetailPrint").innerHTML="";
    obRef.result.hide();

//    obRef.messagebox.hide();
//    obRef.messagebox.reset();


}

function ClearAll (obRef) {
//    obRef.map.layers[0].highlight = "";
    obRef.map.layers[1].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;
}

