﻿
MKSearch = function(config)
{
    Ext.apply(this, config);
    
    var view;
    var viewPageSize = 25;
    
    var loading = Ext.get('rmapSearch-loading');
    var header = Ext.get('rmapSearch-header');
    var footer = Ext.get('rmapSearch-footer');
    
    var emptyHeaderTemplate = "";   
    var lastQueryInfo = null;
    var coordinateSystem = RMap.CoordinateSystem.getCoordinateSystem('EPSG:2170');
    
    
    this.nextQuery = function()
    {
        ds.load({params:{type:'json', content:lastQueryInfo.content, query:lastQueryInfo.query, page: lastQueryInfo.page+1, pageSize:viewPageSize}});
    }
    
    var nextQueryButton = Ext.get('rmapSearch-footer-nextPage');
    nextQueryButton.on('click', this.nextQuery, this);
            
    
    this.onLoad = function()
    {
        lastQueryInfo = ds.reader.jsonData.queryInfo;
        
        loading.setStyle("display", "none");
        
        if(ds.getCount() == viewPageSize)
        {
            footer.setStyle("display", "block")
        }
                
        if(ds.getCount() == 0)
        {
            if(lastQueryInfo.page == 0)
                header.dom.innerHTML += "<br/><br/>" + lngDict["searchNone"];
            else
                header.dom.innerHTML += "<br/><br/>" + lngDict["searchNoMore"];
        }
        
        if(ds.getCount() == 1)
        {
            view.select(0, false, true);
            this.showLocation(view, 0);
        }
    }
    
    this.onBeforeLoad = function()
    {
        ds.removeAll();
        footer.setStyle("display", "none")
        loading.setStyle("display", "block");
    }
    
    this.onLoadException = function(el, proxy, ex)
    {
        loading.setStyle("display", "none");
        header.dom.innerHTML = "ERROR: " + ex.statusText;
    }
    
    
    this.showLocation = function(view, dataIndex)
    {            
        var node = ds.getAt(dataIndex);
				window.manualInfoLoc={x:node.data.bvx, y:node.data.bvy};
        map.openInfoWindow("<b>" + node.data.title + "</b>"+window.routingInsert, node.data.bvx, node.data.bvy, coordinateSystem);
    }
    
    this.zoomLocation = function(view, dataIndex)
    {          
        var node = ds.getAt(dataIndex);
        
        map.setView(node.data.bvx, node.data.bvy, Math.min(map.getZoomLevel(),map.getDetailZoomLevel()));
 				window.manualInfoLoc={x:node.data.bvx, y:node.data.bvy};
        map.openInfoWindow("<b>" + node.data.title + "</b>"+window.routingInsert, node.data.bvx, node.data.bvy, coordinateSystem);
    }
    
    var ds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: applicationSettings.geocodeServiceUri
            }),
            reader: new Ext.data.JsonReader({
                root: 'items'
            }, [
                {name: 'ftype'},
                {name: 'title'},
                {name: 'bvx', type:'float'},
                {name: 'bvy', type:'float'}
            ])
        });
        
    ds.on('load', this.onLoad, this);
    ds.on('beforeload', this.onBeforeLoad, this);
    ds.on('loadexception', this.onLoadException, this);
    
    var tplRpe = new Ext.DomHelper.Template('<a href=""><span class="rpe">{title}</span></a>');
    tplRpe.compile();
    var tplPrs = new Ext.DomHelper.Template('<a href=""><span class="prs">{title}</span></a>');
    tplPrs.compile();
    var tplCeste = new Ext.DomHelper.Template('<a href=""><span class="ceste">{title}</span></a>');
    tplCeste.compile();
    
    this.createView = function(el)
    {
        function reformatDate(feedDate){
            var d = new Date(Date.parse(feedDate));
            return d ? d.dateFormat('D M j, Y, g:i a') : '';
        }
        
        view = new Ext.View(el, '', {store: ds, singleSelect:true, selectedClass:'selected'});
        view.getEl().unselectable();
        
 
        view.on('click', this.showLocation, this);  
        view.on('dblclick', this.zoomLocation, this);
    }
    
           
    this.layout = new Ext.BorderLayout(this.elementId, 
        {
            north: 
            {
                split:false
            },
            center: 
            {
                autoScroll: true
            }
        });
        
    this.layout.add('north', new Ext.ContentPanel(this.elementId + '-north', {fitToFrame: true}));
    var lv = this.layout.add('center', new Ext.ContentPanel(this.elementId + '-center', {fitToFrame: true}));
    this.createView(this.elementId + '-results');
    
  
    function toSQLSafe(unsafeString)
    {
        return unsafeString.replace(/(')/g, "");
    }
    
    
    var rmapSearchRpeQuery = new Ext.form.TriggerField({triggerClass: 'x-form-search-trigger', emptyText:lngDict["searchAdress"]});
    rmapSearchRpeQuery.onTriggerClick = queryRpe;
    rmapSearchRpeQuery.applyTo('rmapSearch-rpeQuery');
    rmapSearchRpeQuery.on("specialkey", queryRpe, this);
    rmapSearchRpeQuery.getResizeEl().dom.style.width = "100%";
        
        
        
        
    function queryRpe( field, e ) 
    {
        if( e.getKey && e.getKey() != e.RETURN && e.getKey() != e.ENTER )
            return;
            
        var queryValue = rmapSearchRpeQuery.getValue();
            
        if( queryValue.length < 2)
            return;
        
        view.tpl = tplRpe;
        header.dom.innerHTML = lngDict["searchAdressRes"] + " <b>" + queryValue + "</b>:";
        ds.load({params:{type:'json', content:'rpe', query:toSQLSafe(queryValue), pageSize:viewPageSize}});
    }
    
     
    
    
    
    
//    var rmapSearchPrsQuery = new Ext.form.TriggerField({triggerClass: 'x-form-search-trigger', emptyText:lngDict["searchPrs"]});
//    rmapSearchPrsQuery.onTriggerClick = queryPrs;
//    rmapSearchPrsQuery.applyTo('rmapSearch-prsQuery');
//    rmapSearchPrsQuery.on("specialkey", queryPrs, this);
//    rmapSearchPrsQuery.getResizeEl().dom.style.width = "100%";
//    
//    function queryPrs( field, e ) 
//    {
//        if( e.getKey && e.getKey() != e.RETURN && e.getKey() != e.ENTER )
//            return;
//            
//        var queryValue = rmapSearchPrsQuery.getValue();
//            
//        if( queryValue.length < 2)
//            return;
//        
//        view.tpl = tplPrs;
//        header.dom.innerHTML = lngDict["searchPrsRes"] + " <b>" + queryValue + "</b>:";
//        ds.load({params:{type:'json', content:'prs', query:toSQLSafe(queryValue), pageSize:viewPageSize}});
//    }
    
    
    
    var rmapSearchCesteQuery = new Ext.form.TriggerField({triggerClass: 'x-form-search-trigger', emptyText:lngDict["searchRoad"]});
    rmapSearchCesteQuery.onTriggerClick = queryCeste;
    rmapSearchCesteQuery.applyTo('rmapSearch-cesteQuery');
    rmapSearchCesteQuery.on("specialkey", queryCeste, this);
    rmapSearchCesteQuery.getResizeEl().dom.style.width = "100%";
    
    
    function queryCeste( field, e ) 
    {
        if( e.getKey && e.getKey() != e.RETURN && e.getKey() != e.ENTER )
            return;
            
        var queryValue = rmapSearchCesteQuery.getValue();
            
        if( queryValue.length < 2)
            return;
        
        view.tpl = tplCeste;
        header.dom.innerHTML = lngDict["searchRoadRes"] + " <b>" + queryValue + "</b>:";
        ds.load({params:{type:'json', content:'ceste', query:toSQLSafe(queryValue), pageSize:viewPageSize}});
    }
    
   
    var rmapSearchCoordQuery = new Ext.form.TriggerField({triggerClass: 'x-form-search-trigger', emptyText:lngDict["coordsSearch"]});
    rmapSearchCoordQuery.onTriggerClick = queryCoord;
    rmapSearchCoordQuery.applyTo('rmapSearch-coordQuery');
    rmapSearchCoordQuery.on("specialkey", queryCoord, this);
    rmapSearchCoordQuery.getResizeEl().dom.style.width = "100%";
    
    
    function queryCoord( field, e ) 
    {
        if( e.getKey && e.getKey() != e.RETURN && e.getKey() != e.ENTER )
            return;


				var val=normalizeString(rmapSearchCoordQuery.getValue());
				var splt=val.split(" ");
				var x=0;
				var y=0;
				var crs="EPSG:2170";
				if(splt.length!=2)
				{
					alertMessage(lngDict["coordsInfo"], "INFO");
					return;
				}
				if(splt[0]!=filterString(splt[0],"1234567890.") || splt[1]!=filterString(splt[1],"1234567890."))
				{
					if(splt[0]==filterString(splt[0],"1234567890.°'′NE") && splt[1]==filterString(splt[1],"1234567890.°'′NE"))
					{
						if(splt[0].endsWith("N") && splt[1].endsWith("E"))
						{
							var tmp=splt[0];
							splt[0]=splt[1];
							splt[1]=tmp;
						}
						x=parseCoord(splt[0]);
						y=parseCoord(splt[1]);
						crs="EPSG:4326";
					}
					if(x==false || y==false)
					{
						alertMessage(lngDict["coordsFormat"], "INFO");
						return;
					}
				}
				else
				{
					x=parseFloat(splt[0]);
					y=parseFloat(splt[1]);
				}
				if(x<=360 && y<=90)
					crs="EPSG:4326";
				if(x>5000000 && y>5000000)
				{
					x-=5000000;
					y-=5000000;
				}
				var info=splt[0] + " " + splt[1];
				map.openInfoWindow(info, x, y, RMap.CoordinateSystem.getCoordinateSystem(crs));
    }
    
    function normalizeString(str)
		{
			while(str.indexOf("  ")>-1)
				str=str.replace("  "," ");
			while(str.length>0 && str.substring(0,1)==" ")
				str=str.substring(1,str.length);
			while(str.length>0 && str.substring(str.length-1,str.length)==" ")
				str=str.substring(0,str.length-1);
			return str;
		}

		function filterString(str,filter)
		{
			var fltStr="";
			for(var f=0;f<str.length;f++)
			{
				var tmp=str.substring(f,f+1);
				if(filter.indexOf(tmp)>-1)
					fltStr+=tmp;
			}
			return fltStr;
		}
		
		function parseCoord(c)
		{
			c=c.replace("°","°|").replace("′","'").replace("''","$|").replace("'","'|").replace("E","").replace("N","");
			c=c.split("|");
			var d=0;
			var m=0;
			var s=0;
			if(c.length>=1 && c[0].indexOf("°")>0)
				d=parseInt(c[0]);
			else
				return false;
			if(c.length>=2 && c[1].indexOf("'")>0)
				m=parseInt(c[1]);
			if(c.length>=3 && c[2].indexOf("$")>0)
				s=parseInt(c[2]);
			return d + (m/60) + (s/3600);
		}
	
	}

