var searchParser = null;
initSearchForm = function(){
     
    app.coordFromMap = function(){
      var r = app.map.getExtent().toArray();
      var dest = new OpenLayers.Projection('EPSG:4326');
      var src = new OpenLayers.Projection('EPSG:102067');
      var j1 = OpenLayers.Projection.transform(new OpenLayers.Geometry.Point(r[0],r[1]), src, dest);
      var j2 = OpenLayers.Projection.transform(new OpenLayers.Geometry.Point(r[2],r[3]), src, dest);
      app.detailSearchForm.getForm().setValues({
        x1: j1.x, y1: j1.y, x2: j2.x, y2: j2.y
      });
    };
     
        
     var partyStore = new Ext.data.JsonStore({
        url: app.mickaPath + '/util/organizace.php?',
        root: 'records',
        id: 'id',
        fields: ['id', 'name']
    });
    
    // simple array store
    var scaleList = new Ext.data.SimpleStore({
        fields: ['value'],
        data : [['1000'],['5000'],['10000'],['50000'],['100000'],['500000'],['1000000']]
    });
    
    var typList = new Ext.data.SimpleStore({
      data: [['data','data'],['service',HS.i18n('service')]],
      fields: ['kod', 'label']
    });

  // --- XML cteni ---  
  var topicsRecordDef = Ext.data.Record.create([
     {name: 'name', mapping: '@name'},     // "mapping" property not needed if it's the same as "name"
     {name: 'label', mapping: '/'}                 // This field will use "occupation" as the mapping.
  ]);
  var topicsReader = new Ext.data.XmlReader({
     //totalRecords: "results", // The element which contains the total dataset size (optional)
     record: "topicCategory/value"           // The repeated element which contains row information
     //id: "id"                 // The element within the row that provides an ID for the record (optional)
  }, topicsRecordDef);  
    
   var topicsStore = new Ext.data.Store({
      url: 'xsl/codelists_'+HS.getLang()+'.xml',
      reader: topicsReader,
      autoload: true
   });

  var serviceRecordDef = Ext.data.Record.create([
     {name: 'name', mapping: '@name'},     // "mapping" property not needed if it's the same as "name"
     {name: 'label', mapping: '/'}                 // This field will use "occupation" as the mapping.
  ]);

  var serviceTypeReader = new Ext.data.XmlReader({
     //totalRecords: "results", // The element which contains the total dataset size (optional)
     record: "LocalName/value"           // The repeated element which contains row information
     //id: "id"                 // The element within the row that provides an ID for the record (optional)
  }, serviceRecordDef);  
    
   var serviceStore = new Ext.data.Store({
      url: 'xsl/codelists_'+HS.getLang()+'.xml',
      reader: serviceTypeReader,
      autoload: true
   });
  
   topicsStore.load();
   serviceStore.load();

  var kw = new Ext.form.TriggerField(
  	{fieldLabel: HS.i18n('Keywords'), name:'keywords'}
  );
  kw.onTriggerClick = app.showGemet;
  
  
  //var theMap = Ext.get('map');   
  var searchForm = new Ext.FormPanel({
    
    frame:true,
    //defaultType: 'textfield',
    //border:false,
    width: 800,
    items: [{
        layout:'column',
        labelWidth: 75,
        items:[{
          width:350,        
          layout: 'form',  
              defaults: {width: 230},
              defaultType: 'textfield',
              items :[{
                      name: 'title',
                      selectOnFocus:true,
                      fieldLabel: HS.i18n('Title'),
                      minChars: 3
              		},kw,
              		{
                      name: 'party',
                      xtype: 'combo',  
                      store: partyStore,
                      displayField:'name',
                      typeAhead: false,
                      triggerAction: 'all',
                      selectOnFocus:true,
                      fieldLabel: HS.i18n('Organization'),
                      autoLoad: true, 
                      minChars: 1
                  }, {
 
                      xtype: 'combo',
                      store: typList,
                      fieldLabel:HS.i18n('Resource'),
                      displayField:'label',
                      valueField: 'kod',
                      forceSelection: true,
                      hiddenName: 'hlevel',
                      typeAhead: true,
                      selectOnFocus:true,
                      triggerAction: 'all',
                      mode:'local',
                      listeners: {'click': {fn: app.coordFromMap, scope:this}}
                      
                  },{
                      xtype: 'combo',  
                      fieldLabel: HS.i18n('Service'),
                      id: 'service-select',
                      displayField:'label',
                      valueField: 'name',
                      hiddenName: 'serviceType',
                      typeAhead: true,
                      store: serviceStore,
                      triggerAction: 'all',
                      mode:'local'
                  },{
                      xtype: 'combo',  
                      fieldLabel:HS.i18n('Topic'),
                      displayField:'label',
                      valueField: 'name',
                      forceSelection: true,
                      hiddenName: 'topic',
                      typeAhead: true,
                      store: topicsStore,
                      triggerAction: 'all',
                      //disabled: true,
                      mode:'local'
                  },{
                        xtype: 'panel',
                        layout: 'column',
                        width: 340,
                        items:[{
                              width: 180,
                              layout: 'form',
                              items:[{
                                      xtype: 'combo',
                                      store: scaleList,
                                      displayField: 'value',
                                      fieldLabel: HS.i18n('Scale from')+' 1',
                                      width: 95,
                                      name: 'scale1',
                                      triggerAction: 'all',
                                      mode:'local'
                                  },{
                                      xtype: 'datefield',
                                      format: 'd.m.Y',
                                      fieldLabel: HS.i18n('Date from'),
                                      //width: 100,
                                      name: 'date1'
                                  }]
                            },{
                              //columnWidth: .5,
                              labelWidth: 30,
                              layout: 'form',
                              items:[{
                                      xtype: 'combo',
                                      store: scaleList,
                                      displayField: 'value',
                                      fieldLabel: HS.i18n('to')+ ' 1',
                                      width: 95,
                                      name: 'scale2',
                                      triggerAction: 'all',
                                      mode:'local'
                                  },{
                                      fieldLabel: HS.i18n('to'),
                                      xtype: 'datefield',
                                      format: 'd.m.Y',
                                      //width: 100,
                                      name: 'date2'
                                  }]
                            }]
                    }]
      },{
          width:370,
          defaults: {labelWidth: 10},
          layout: 'form',
          items: [/*{   
                //contentEl:"map",
                collapsible: false,
                split:true,
                layout:'fit'
            },*/{ 
                layout: 'column',
                items: [{
                        columnWidth:.2,                     
                        defaults: {width: 45},
                        layout: 'form',
                        items: [{
                            fieldLabel: 'Z',
                            xtype: 'numberfield',
                            name: 'x1'
                        }]
                    },{
                        columnWidth:.2,        
                        defaults: {width: 45},
                        layout: 'form',
                        items: [{fieldLabel: 'J',
                              xtype: 'numberfield',
                              name: 'y1'}]
                    },{
                        columnWidth:.2,        
                        defaults: {width: 45},
                        layout: 'form',
                        items: [{fieldLabel: 'V',
                              xtype: 'numberfield',
                              name: 'x2'}]
                    },{
                        columnWidth:.2,        
                        defaults: {width: 45},
                        layout: 'form',
                        items: [{fieldLabel: 'S',
                              xtype: 'numberfield',
                              name: 'y2'}]
                    },
                    {
                        columnWidth:.2,        
                        defaults: {width: 40},
                        layout: 'form',
                        items: [{xtype:'button', cls: 'x-btn-icon', icon:'img/globe.gif', tooltip: HS.i18n('From map'), handler: app.coordFromMap}]
                    }]        
              }]       
          }]
      }],
        buttons: [{
            text: HS.i18n('Search'),
            handler: function(){
              var vysl = Ext.get('vysledky');
              formValues = searchForm.getForm().getValues();
              var qstr = searchParser.parse(formValues);
              var a = Ext.get('service-select');
              //alert(qstr);
              mickaView.store.baseParams.query=qstr;
      		  mickaView.store.load({params:{'start':0}});
      		  //mickaView.store.load();
            }
        },{
            text: HS.i18n('Clear'),
              handler: function(){
              formValues = searchForm.getForm().reset();
              //mmeta.deleteBox();
            }

       }]
  });
  
  searchParser = new MdExtFormParser();
  return searchForm;
  
}    

function MdExtFormParser(){
  //this.formValues = values;
  this.qstr = '';
  this.AND = '+';
  this.OR = '|';

  this.parseTextField = function(s, name, lk){
  	if(!s) return '';
    if(s.indexOf(this.OR)==-1) var tokens=[s];
    else var tokens = s.split(this.OR);
    for(var i=0;i<tokens.length;i++){
     	if(tokens[i].indexOf(this.AND)>-1){
    		var atokens = tokens[i].split(this.AND);
    		for(var j=0;j<atokens.length;j++){
    			if(lk) atokens[j] = name+" like '*" + atokens[j].trim() + "*'";
    			else atokens[j] = name+"='"+atokens[j].trim()+"'";
    		}
    		tokens[i] = "("+atokens.join(" AND ")+")";
    	}
    	else{
    		if(lk) tokens[i]= name+" like '*"+tokens[i].trim()+"*'";
    		else tokens[i]= name+"='"+tokens[i].trim()+"'";
    	}
    }
    s = tokens.join(" OR ");
    if(tokens.length>1) s = "("+s+")";
    return s;
  }
  
  this.add = function(s){
   	if(!s) return;
  	if(this.qstr) this.qstr += " AND ";
  	this.qstr += s;   	
  }

  this.addQuery = function(str, name, lk){
  	if(str){ 
  		//if(typeof(str)!=typeof('aaa')) str = str.value;
  		this.add(this.parseTextField(str,name,lk));
  	}	
  }

  this.parse = function(f){
  	//var f = this.formValues;
  	this.qstr = '';
	this.addQuery(app.searchField.getValue(),'anytext',true);
    this.addQuery(f.title,'title',true);
    this.addQuery(f.keywords,'subject',false);
    this.addQuery(f.topic,'TopicCategory',false);
    this.addQuery(f.party,'OrganisationName',false);
    /*if(f.org){
    	var o=[];
       	for(var i=0;i<f.org.length;i++) if(f.org[i]) o.push(f.org[i]);
    	this.addQuery(o.join(','),'OrganisationName',true);
    }*/
    if(f.x1) this.add("bbox='"+f.x1+" "+f.y1+","+f.x2+" "+f.y2+"'");
	if(f.date1) this.add("TempExtent_begin>="+date2iso(f.date1));
	if(f.date2) this.add("TempExtent_end<="+date2iso(f.date2));
	if(f.modified) this.add("modified>="+date2iso(f.modified));
	if(f.scale1) this.add("Denominator>="+f.scale1);
	if(f.scale2) this.add("Denominator<="+f.scale2);
	if(f.hlevel){
		if(f.hlevel=='data') this.add("(Type=dataset OR Type=series)");
		else {
			this.addQuery(f.hlevel,'Type',false);
			this.addQuery(f.serviceType,'ServiceType',false);
		}	
	}
	this.addQuery(f.language,'Language',false);	
    return this.qstr;
  } 
}//end class

  function date2iso(d){
  	if(d.indexOf('.')>-1){
  		var s = d.split('.');
  		if(s[2]) d = s[2]+'-'+s[1]+'-'+s[0];
  		else d = s[1]+'-'+s[0];
  	}
  	return d;
  }


  HS.Lang["cze"]["to"] = "do";
  HS.Lang["cze"]["service"] = "služba";
  HS.Lang["cze"]["Service"] = "Služba";
  HS.Lang["cze"]["Resource"] = "Typ zdroje";
  HS.Lang["cze"]["Topic"] = "Téma";
  HS.Lang["cze"]["Keywords"] = "Klíč. slova";
  HS.Lang["cze"]["Organization"] = "Organizace";
  HS.Lang["cze"]["Scale from"] = "Měřítko od";
  HS.Lang["cze"]["Date from"] = "Datum od";
  

