﻿ if(typeof MS == "undefined") MS = {};
 if(typeof MS.Web == "undefined") MS.Web = {};
 if(typeof MS.Web.AutoComplete == "undefined") MS.Web.AutoComplete = {};


MS.Web.AutoComplete = Class.create();

var searchType="basic";

Object.extend(MS.Web.AutoComplete.prototype,
{
   timer : null,
   count : 21,
   pos : - 1,
   waitAfterInput : 200,
   minChars : 2,
   children : null,

   changeHighlight : function(){
	   var l;
	   try{
		  l = this.getLength();
	      
		  for(var i = 1; i < this.count && i < l; i ++ ){
			 if(i == this.pos)
				this.div.childNodes[i].className = "selected";
			 else
				this.div.childNodes[i].className = "item"
		  }
      }catch(err){}
   }
   ,
   getItem : function(idx)
   {
      return null;
   }
   ,
   getLength : function()
   {
      return 0;
   }
   ,
   getDisplay : function(item)
   {
      return item;
   }
   ,
   getValue : function(item)
   {
      return item;
   }
   ,
   hide : function()
   {
      this.div.style.display = "none";
      this.iFrame.style.display="none";
   }
   ,
   show : function()
   {
      try{
        this.changeHighlight();
        this.div.style.display = "inline";
        this.iFrame.style.display="inline";
      }catch(er){}
   }
   ,
   focusTextbox : function()
   {
      this.ele.focus();
   }
   ,
   select : function()
   {
      if(searchType == "advanced"){
		AutoCompleteClearTxtBs();
      }
      
      if(this.getLength() > 1 && this.pos <=0)
		this.pos = 1;
      
      if(this.pos > - 1)
      {
         var v = this.getValue(this.getItem(this.pos-1));
         if(v != this.ele.value)
         {
            this.ele.value = v;
            if(this.children != null)
            for(var i = 0; i < this.children.length; i ++ )
            {
               this.children[i].onparentchange(v);
            }
         }
      }
      
      this.hide();
   }
   ,
   onkeydown : function(e)
   {
      var key = MS.Keys.getCode(e);
      switch(key)
      {
         case MS.Keys.TAB :
         case MS.Keys.ENTER :
            this.select();
            if(key == MS.Keys.ENTER) MS.cancelEvent(e);
            break;


         case MS.Keys.ESC :
            this.hide();
            break;


         case MS.Keys.KEYUP :
            if(this.pos > 0) this.pos -- ;
            this.changeHighlight();
            break;


         case MS.Keys.KEYDOWN :
            if(this.pos < this.getLength() - 1 && this.pos < this.count - 1)
            this.pos ++ ;
            this.changeHighlight();
            break;
      }
   }
   ,
   onkeyup : function(e)
   {
      switch(MS.Keys.getCode(e))
      {
         case MS.Keys.TAB :
         case MS.Keys.ENTER :
         case MS.Keys.ESC :
         case MS.Keys.KEYUP :
         case MS.Keys.KEYDOWN :
         case MS.Keys.KEYLEFT :
         case MS.Keys.KEYRIGHT :
         case MS.Keys.ALT :
         case MS.Keys.SHIFT :
         case MS.Keys.CTRL :
         break;


         default :
         if(this.ele.value.length < this.minChars)
         return false;


         if(this.timer != null) clearTimeout(this.timer);
         this.timer = setTimeout(this.getData.bind(this), this.waitAfterInput);
         break;
      }
   }
   ,
   onfocus : function(e)
   {
      this.changeHighlight();
   }
   ,
   onblur : function(e)
   {
      setTimeout(this.hide.bind(this), 200);
      // 200 msec for onclick event of item
   }
   ,
   onmouseover : function(e)
   {
      this.pos = MS.getTarget(e).idx;
      this.changeHighlight();
   }
   ,
   onclick : function(e)
   {
      this.pos = MS.getTarget(e).idx;
      this.changeHighlight();
      this.select();
   }
   ,
   ondblclick : function(e)
   {
      if(this.ele.value == "")
      this.getData();
   }
   ,
   onchange : function(e)
   {
      if(this.children != null)
      for(var i = 0; i < this.children.length; i ++ )
      {
         this.children[i].onparentchange(this.ele.value);
      }
   }
   ,
   onparentchange : function(v)
   {
      this.ele.value = "";
   }
   ,
   updateList : function(valid)
   {
   try{
      var l = this.getLength();
      this.pos = 0;

			  if(l > 1){
				this.div.childNodes[0].innerHTML = "<b>Please select from the list below<b>";
				this.div.childNodes[0].style.display = "block";
				this.div.childNodes[0].className = "itemsHeader";
			  }
			  for(var i = 1; i < l+1 && i < this.count; i ++ )
			  {

				 this.getDisplay(this.getItem(i-1));
				 this.div.childNodes[i].innerHTML = this.getDisplay(this.getItem(i-1));
				 this.div.childNodes[i].style.display = "block";
			  }
      
      
		      
			  if(this.pos > l) this.pos = this.getLength() - 1;


			  for(var i = l; i < this.count; i ++ )
			  {
				 this.div.childNodes[i].style.display = "none";
			  }


			  if(this.pos > l - 1)
			  {
				 this.pos = l - 1;
			  }


			  if(this.div.childNodes[0].clientHeight == 0)
			  {
				 this.show();
				 this.updateList(valid);
				 return;
			  }


			  var h = (l < this.count ? l : this.count) *  this.div.childNodes[0].clientHeight;


			  if(h > 0)
			  {
				 this.div.style.height = h + "px";
				 this.iFrame.style.height = (h-2)+"px";
				 this.show();
			  }
			  else
				this.hide();
      }catch(err){
		//alert(err);
         this.hide();
      }
   }
   ,
   getData : function()
   {
   }
   ,
   ondata : function()
   {
      this.updateList();
   }
   ,
   onresize : function()
   {
      var r = MS.Position.getBounds(this.ele);
      //this.ele.rect = r;
      
      if(navigator.appName == "Microsoft Internet Explorer"){
        r.top = findPosY(this.ele) + r.height +10;
        r.left = findPosX(this.ele)+4;
      }else{
        r.top = findPosY(this.ele) + r.height;
        r.left = findPosX(this.ele);  
      }
      
      MS.Position.setLocation(this.div, r);
      MS.Position.setLocation(this.iFrame, r);
      delete r;
   }
   ,
   initialize: function (id, count, parent) 
   {
      this.ele = document.getElementById(id);
      if(this.ele == null || this.ele.tagName != "INPUT") throw "Control could not be found.";
      this.count = count != null && ! isNaN(count) ? count : this.count;


      if(parent != null)
      {
         // no the parent control, instance of MS.Web.AutoComplete
         parent.children = [];
         parent.children.push(this);
      }


      addEvent(this.ele, "keydown", this.onkeydown.bind(this));
      addEvent(this.ele, "keyup", this.onkeyup.bind(this));
      addEvent(this.ele, "blur", this.onblur.bind(this));
      addEvent(this.ele, "focus", this.onfocus.bind(this));
      addEvent(this.ele, "change", this.onchange.bind(this));
      addEvent(this.ele, "dblclick", this.ondblclick.bind(this));


      // build list
      
      this.div = document.createElement("div");
      document.body.appendChild(this.div);

      //IFrame 
      this.iFrame = document.createElement("iframe");
      this.iFrame.id = this.ele.id+"_iframe";
      this.iFrame.src="javascript:false;";
      this.iFrame.scrolling="no";
      this.iFrame.border="0";
      this.iFrame.style.position="absolute";
      this.iFrame.style.top="0px";
      this.iFrame.style.left="0px";
      this.iFrame.style.display="none";
      document.body.appendChild(this.iFrame);
  
      // see iframe ajaxpro
      this.div.id = this.ele.id + "_list";
      this.div.style.className ="autoComplete_list";

      this.div.style.display = "none";
//      this.div.style.border = "1px solid #ccc";
//      this.div.style.borderRight ="none";
      this.div.style.zIndex="100";
      
      if(navigator.appVersion.indexOf("MSIE 6.0") > -1){
			this.div.style.border="solid 1px #ccc";
      }else{
		  this.div.style.padding="0px 9px 9px 0px";
		  this.div.style.backgroundImage = "url(images/dropBg.png)";
		  this.div.style.backgroundPositionX="right";
		  this.div.style.backgroundPositionY="bottom";
		  this.div.style.backgroundRepeat = "no-repeat";
      }
     // this.div.style.backgroundColor="white";
      
      //this.div.style.background="green";
      


      var r = MS.Position.getBounds(this.ele);
      this.ele.rect = r;
      
      //alert(r.width+","+r.height);
      var posY = findPosY(this.ele);
      var posX = findPosX(this.ele);
      if(navigator.appName == "Microsoft Internet Explorer"){
        r.top =  posY+ r.height +10;
        r.left = posX +1;
      }else{
        r.top = posY + r.height;
        r.left = posX;  
      }      
	  
      MS.Position.setBounds(this.div, r);
      MS.Position.setBounds(this.iFrame, r);
     
	  if(r.width > 235){
		this.div.style.width = r.width + "px";
		this.iFrame.style.width = (r.width-10) + "px";
	 }else{
		this.div.style.width = "245px";
		this.iFrame.style.width = "235px";
	 }
      
      this.iFrame.style.zIndex = "99";


      for(var i = 0; i < this.count; i ++ )
      {
         var d = document.createElement("div");
         this.div.appendChild(d);
         d.style.width = this.ele.clientWidth;
         //d.style.height = r.height + "px";
         d.style.whiteSpace = "nowrap";
         d.style.overflow = "hidden";
         d.className = this.ele.id + "_item";
         d.style.width ="235px";
         d.idx = i;

         addEvent(d, "mouseover", this.onmouseover.bind(this));
         addEvent(d, "click", this.onclick.bind(this));


         MS.setText(d, " ");
      }
      addEvent(window, "resize", this.onresize.bind(this));
      delete r;
      if(searchType == "advanced" && navigator.appName != "Microsoft Internet Explorer")
		addEvent(window, "load", this.onresize.bind(this));
   }
}
, false);


MS.Web.AutoCompleteDataTable = Class.create();
Object.extend(MS.Web.AutoCompleteDataTable.prototype,
MS.Web.AutoComplete.prototype, true);

Object.extend(MS.Web.AutoCompleteDataTable.prototype,
{
   dt : null,
   getItem : function(idx)
   {
      if(idx >= 0 && idx < this.dt.Rows.length)
      return this.dt.Rows[idx];
      return null;
   }
   ,
   getLength : function()
   {
      if(this.dt != null && this.dt.Rows != null)
      {
         return this.dt.Rows.length+1;
      }
      return 0;
   }
   ,
   callback : function(res)
   {
   //alert('CallBack');
      if(res.error != null)
      {
       //   alert(res.error.Message);
         return;
      }
      if(res.value.Rows.length > 0 ){// || (this.dt.Rows == null || this.dt.Rows.length == null )){
		this.dt = res.value;		
		this.ondata();
      }else{
		/*if(this.dt.Rows.length < 2)
			this.dt = res.value;
		this.ondata();*/
		this.div.childNodes[0].innerHTML ="<span style=\"color:#c00\">No matches for <b>\""+this.ele.value+"\"</b></span>";
      }
      
   }



}
, true);


   function findPosY(obj)
   {
      var curtop = 0;
      if (obj.offsetParent)
      {
         while (obj.offsetParent)
         {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
         }
      }
      else if (obj.y) curtop += obj.y;
      return curtop;
   }
  function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }


function AutoCompleteClearTxtBs(){
    try{
        document.formSearchLoc.Airports.selectedIndex = 0;
	    document.formSearchLoc.Seaports.selectedIndex = 0;
	    document.formSearchLoc.TownCityName.value ='';
	    document.formSearchLoc.County.value='';
	    document.formSearchLoc.Postcode.value='';
	    document.formSearchLoc.TubeStations.selectedIndex=0;
	    document.formSearchLoc.JunctionName.value = '';
	}catch(err){
	    alert(err);
	}
}

function UpdateSearchData(text, coord){
    try{
        if(searchType == "advanced"){
            if(coord != "0")
                document.getElementById("LocationCoordinates").value = coord;
            else
                document.getElementById("LocationCoordinates").value ="";
                
            document.getElementById("LocationNameHiddenField").value = text;
            
            if(coord != "0")
                AutoJumpToLocation(text, coord);
       }else if( searchType == "basic"){
            var searchPanelID = getSearchPanelID();
             if(coord != "0")
                document.getElementById(searchPanelID+"_LocationCoordinates").value = coord;
            else
                document.getElementById(searchPanelID+"_LocationCoordinates").value ="";
                
            document.getElementById(searchPanelID+"_LocationNameHiddenField").value = text;
            
       }
    }catch(err){
        alert("Could not update search data. "+err);
    }
}

function init() {
    searchType = "advanced";
    var cityTxtbName = document.getElementById("tCNTxtbHolder").value;
    var cityAuto = new MS.Web.AutoCompleteDataTable(cityTxtbName, 21);

    cityAuto.getDisplay = function(item) {
        return (item != null ? item.town.toString()+", "+item.county.toString() : "");
    }
    cityAuto.getValue = function(item) {
        try{
            if(item !=null){
                UpdateSearchData(item.town.toString()+", "+item.county.toString() , item.gridx.toString()+","+item.gridy.toString());
            }
        }
        catch(err){
            alert(err);
        }
        return (item != null ? item.town.toString()+", "+item.county.toString() : "");
    }
    cityAuto.getData = function() {
        venuefinder.search_loc.SearchTownsAndCities(this.ele.value, this.count, this.callback.bind(this));
    }
	
    var countyTxtbName = document.getElementById("countyTxtbHolder").value;
    var countyAuto = new MS.Web.AutoCompleteDataTable(countyTxtbName, 21);
    countyAuto.getDisplay = function(item) {
        return (item != null ? item.county.toString().trimRight() : "");
    }
    countyAuto.getValue = function(item) {
         try{
            if(item !=null){
                UpdateSearchData(item.county.toString().trimRight(), "0");
                load(); // Clears map cursor on Google map.
            }
        }
        catch(err){
            alert(err);
        }
        return (item != null ? item.county.toString().trimRight() : "");
    }
    countyAuto.getData = function() {
        venuefinder.search_loc.SearchCounties(this.ele.value, this.count, this.callback.bind(this));
    }
	
	
    var motorwayTxtBName = document.getElementById("mWayTxtBHolder").value;
    var motorwayAuto = new MS.Web.AutoCompleteDataTable(motorwayTxtBName, 21);
    motorwayAuto.getDisplay = function(item) {
        return (item != null ? item.Description.toString().trimRight() : "");
    }
    motorwayAuto.getValue = function(item) {
        try{
            if(item !=null){
                UpdateSearchData(item.Description.toString().trimRight(), item.Coords.toString());
            }
        }
        catch(err){
            alert(err);
        }
        return (item != null ? item.Description.toString().trimRight(): "");
    }
    motorwayAuto.getData = function() {
        venuefinder.search_loc.SearchMotorwayJunction(this.ele.value, this.count, this.callback.bind(this));
    }
    
    var railwayClientID = document.getElementById("railwayClientIDHolder").value;
    var railwayAuto = new MS.Web.AutoCompleteDataTable(railwayClientID, 21);
    railwayAuto.getDisplay = function(item) {
        return (item != null ? item.Description.toString().trimRight() : "");
    }
    railwayAuto.getValue = function(item) {
        try{
            if(item !=null){
                UpdateSearchData(item.Description.toString().trimRight(), item.Coords.toString());
            }
        }
        catch(err){
            alert(err);
        }
        return (item != null ? item.Description.toString().trimRight(): "");
    }
    railwayAuto.getData = function() {
        venuefinder.search_loc.SearchRailwayStations(this.ele.value, this.count, this.callback.bind(this));
    }
    
    
}
        
function InitSearchPanelTown() {
	//addEvent(window, "load", LoadSearchPanelTown);
	LoadSearchPanelTown();
	LoadSearchPanelCounty();
}

function LoadSearchPanelTown(e){
	searchType = "basic";
	var textBoxName = getSearchPanelID() + "_TownSearchTextBox";
	var cityAutoMain = new MS.Web.AutoCompleteDataTable(textBoxName, 21);

    cityAutoMain.getDisplay = function(item) {
        return (item != null ? item.town.toString()+", "+item.county.toString() : "");
    }
    cityAutoMain.getValue = function(item) {
        try{
            if(item !=null){
                UpdateSearchData(item.town.toString()+", "+item.county.toString() , item.gridx.toString()+","+item.gridy.toString());
            }
        }
        catch(err){ alert("GetValue "+item); }
        return (item != null ? item.town.toString()+", "+item.county.toString() : "");
    }
    
    cityAutoMain.getData = function() {
		venuefinder.controls.SearchPanel.GetTownsForAjax(this.ele.value, this.count, this.callback.bind(this));
    }
}

function LoadSearchPanelCounty(e){
	var textBoxName = getSearchPanelID() + "_CountyTextBox";
	var countyTable = new MS.Web.AutoCompleteDataTable(textBoxName, 21);

    countyTable.getDisplay = function(item) {
        return (item != null ? item.county.toString() : "");
    }
    countyTable.getValue = function(item) {
        return (item != null ? item.county.toString().trimRight() : "");
    }
    countyTable.getData = function() {
		venuefinder.controls.SearchPanel.GetCountiesForAjax(this.ele.value, this.count, this.callback.bind(this));
    }
}
