//               # area drop down  #
//  localityBox variable is used for send textBox id to all functions to manipulation with text box 

var browser = navigator.userAgent.toLowerCase();
var IE = browser.indexOf("msie") != -1;
var Opera = browser.indexOf("opera") != -1;
var Safari = browser.indexOf("safari") != -1;
var Crome = browser.indexOf("crome") != -1;

var locations = new Array(); //This array will store areas to be loaded by AJAX.
var loadlistlocations = new Array(); //This array will store areas for loadlist to be loaded by AJAX.
var resalelocations = new Array(); //This array will store areas for resaleloadlist to be loaded by AJAX.
var searcherlocations = new Array(); //This array will store areas for SearcherRequirmentloadlist to be loaded by AJAX.
var valuationlocations = new Array(); //This array will store areas for valustionlist to be loaded by AJAX.

var projectnames = new Array();
var _Curr = 0;
var NUMBER_OF_RESULTS = 10; //no of Suggestions
var availableResults = 0;

var show = true;
var wait="Please Wait...Loading Localities... ";
var ready="Please Enter Locality";

//This variable maintains listing_type value. Need it to determine whether AJAX call for areas to be fired or not.
//The call is made only when transition is made from rent to rest 3 values and vice versa
var old_listing_type;

// this function is called on key press on all locality box, this check which key is pressed.
// loadProject is a flag to identify that request is come form load list property.
function init(ev,localityBox) {
    var key = window.event ? window.event.keyCode : ev.keyCode;    
    var RETURN = 13;
    var TAB = 9;
    var ESC = 27;
    var bubble = true;
    show = true;
    switch (key) {
      case RETURN:
      case TAB:
      case ESC:
        bubble = false;
        clearSuggestions();
        break;
      default:;
    }
    return bubble;
}

// this function is called on key up on all locality box, this generate suggetions drop down
 // in this function parameters are event, id of text box where event generate and array that has suggetion options.
function suggest(ev,localityBox,arrayForSuggestion) {
    var key = window.event ? window.event.keyCode : ev.keyCode;
    var ARRUP = 38;
    var ARRDN = 40;
    var bubble = true;
    switch (key) {
      case ARRUP:
        changeHighlight("up",localityBox);
        bubble = false;
        break;
      case ARRDN:
        changeHighlight("down",localityBox);
        bubble = false;
        break;        
      default:      
        getSuggestions(bObject(localityBox).value,localityBox,arrayForSuggestion);
    }
    return bubble;
}

function restoreAll() {
    var total = NUMBER_OF_RESULTS >= availableResults ? availableResults : NUMBER_OF_RESULTS;
    for (var i = 0; i < total; i++) {
        try {
            restore(bObject("suggest_" + i));
        } catch (e) {
        }
    }
}

function restore(elem) {
    elem.className = "suggestNormal";
}

function highlight(elem) {
    elem.className = "suggestHover";
}

function changeHighlight(key,localityBox) {
    var obj = false;
    try {
        obj = bObject("suggest");
    } catch (e) {
    }
    if (obj) {
        var sugg = false;
        try {
            sugg = bObject("suggest");
        } catch (e) {
        }
        if (sugg) {
            var currElem = "suggest_1";
            var currObj = false;
            try {
                currObj = bObject(currElem);
            } catch (e) {
            }
            if (currObj) {
                var total = NUMBER_OF_RESULTS >= availableResults ? availableResults : NUMBER_OF_RESULTS;
                for (var i = 1; i <= total; i++) {
                    try {
                        restore(bObject("suggest_" + i));
                    } catch (e) {
                    }
                }
                if (key == "up") {
                    if (_Curr != 0) {
                        _Curr -= 1;
                    }
                } else if (key == "down") {
                    if (_Curr != total) {
                        _Curr += 1;
                    }
                }
                currElem = "suggest_" + _Curr;
                try {
                    currObj = bObject(currElem);
                } catch (e) {
                }
                if (currObj) {
                    highlight(currObj);
                    populate(currObj,localityBox);
                }
            } else {
                try {
                    restore(bObject("suggest_" + _Curr));
                } catch (e) {
                }
                if (_Curr > 0) {
                    _Curr -= 1;
                } else {
                    _Curr = -1;
                }
            }
        }
    }
}

function populate(currObj,localityBox) {
    var tokens = bObject(localityBox).value.split(",");
    var tokenisedInput = "";
    for (var k = 0; k < tokens.length; k++) {
        if (k != tokens.length - 1) {
            tokenisedInput += trim(tokens[k]) + ", ";
        }
    }
    tokenisedInput += stripTags(currObj.innerHTML);
    tokenisedInput=tokenisedInput.split(' (');
    bObject(localityBox).value = tokenisedInput[0];
    bObject(localityBox).focus();
}

function stripTags(str) {
    var stripped = str.replace(/(<([^>]+)>)/gi, "");
    return stripped;
}

// this function is called for create div for suggetion and call createdropdown(); 
function getSuggestions(str,localityBox,arrayForSuggestion) {
    if (show) {
        var input = str.toLowerCase();
        var tokens = input.split(",");
        input = trim(tokens[tokens.length - 1]);
        _Curr = 0;
        var len = input.length;
        var results = new Array;
        var suggestions = new Array;
        if (len) {
            for (var i = 0; i < arrayForSuggestion.length; i++) {
                if (arrayForSuggestion[i].substring(0, len).toLowerCase() == input) {
                    results[results.length] = "<b>" + arrayForSuggestion[i].substring(0, len) + "</b>" + arrayForSuggestion[i].substring(len, arrayForSuggestion[i].length);
                    if (results.length == NUMBER_OF_RESULTS) {
                        break;
                    }
                } else {
                    var start = arrayForSuggestion[i].toLowerCase().indexOf(" " + input);
                    if (start > 0 && suggestions.length < NUMBER_OF_RESULTS) {
                        var suggestion = arrayForSuggestion[i].substring(0, start) + "<b>" + arrayForSuggestion[i].substring(start, start + len + 1) + "</b>" + arrayForSuggestion[i].substring(start + len + 1, arrayForSuggestion[i].length);
                        suggestions[suggestions.length] = suggestion;
                    }
                }
            }
        }
        var result = results.length > 0 ? results : suggestions;
        createDropDown(result,localityBox);
    } else {
       show = true;
    }
}

// this function is called for change suggestion on keyprss and key keyup
 function createDropDown(results,localityBox) {
    var y = posY(localityBox);
    var x = posX(localityBox);
    var w = bObject(localityBox).clientWidth;
    try {
        document.getElementsByTagName("body")[0].removeChild(bObject("suggest"));
    } catch (e) {}
    var div = document.createElement("div");
    div.id = "suggest";
    div.style.position = "absolute";
    div.style.left = x + 1 + "px";
    div.style.top = y + bObject(localityBox).clientHeight + "px";
    div.style.width = w - 2 + "px";
    if (Safari) {
        div.style.top = parseInt(div.style.top) + "px";
        div.style.width = w - 1 + "px";
    }
    
    if (Crome) {
        div.style.top = parseInt(div.style.top) + "px";
        div.style.width = w - 1 + "px";
    }

    if (IE) {
        div.style.left = parseInt(div.style.left) + "px";
        div.style.top = parseInt(div.style.top) + "px";
        div.style.width = w - 2 + "px";
    }
    div.className = "suggestContainer";
    document.getElementsByTagName("body")[0].appendChild(div);
    div.innerHTML = "";
    if (results.length == 0) {
        div.style.display = "none";
    }
    else {
        div.style.display = "";
    }
    for (var i = 1; i <= results.length; i++) {
         
         var pipeRegex = /\|/;   
        
       if(results[i - 1].match(pipeRegex)=='|')       
        {
          var areaAndList= results[i - 1].split('|');       
          var mouseaction = "onmouseover='restoreAll();highlight(this);_Curr=" + i + ";' onmouseout='restore(this)' onclick = populate(this,'"+localityBox+"');clearSuggestions();";
          div.innerHTML += "<div class='suggestNormal' id='suggest_" + i + "' " + mouseaction + ">" + areaAndList[0] + "</></div>";
        }
        else
        {
          var mouseaction = "onmouseover='restoreAll();highlight(this);_Curr=" + i + ";' onmouseout='restore(this)' onclick = populate(this,'"+localityBox+"');clearSuggestions();";
        div.innerHTML += "<div class='suggestNormal' id='suggest_" + i + "' " + mouseaction + ">" + results[i - 1]+"</div>";
        }
    }div.innerHTML = div.innerHTML + "<div id='inputSearchTagDiv'>Select with mouse or arrow keys ( &#8593;&nbsp;&#8595; ) and press Enter</div>";
    availableResults = results.length;
}

// this function is called for clesr suggtion on area drop down 
  function clearSuggestions() {
    try {
        document.getElementsByTagName("body")[0].removeChild(bObject("suggest"));
    } catch (e) {
    }
    show = false;
  }

//Finds the absolute X position (integer value) of a object on screen. The agrgument to be passed is elements id.
//This function is absolutely independent of the style.position attribute of the element.
function posX(element){
  try{
    var obj=bObject(element);
    var curleft = 0;
    if (obj.offsetParent){
      while (obj.offsetParent){
        curleft += obj.offsetLeft;
        obj = obj.offsetParent;
      }
    }else if (obj.x){
      curleft += obj.x;
    }
    return curleft;
  }catch(e){}
}

//Finds the absolute Y position (integer value) of a object on screen. The agrgument to be passed is elements id.
//This function is absolutely independent of the style.position attribute of the element.
 function posY(element){
  try{var obj=bObject(element);
    var curtop = 0;
    if (obj.offsetParent){
      while (obj.offsetParent){
        curtop += obj.offsetTop;
        obj = obj.offsetParent;
      }
    }else if (obj.y){
      curtop += obj.y;
    }
    return curtop;
  }catch(e){}
}


// returns the object of an html element  *
var bObject = function(a){
    if(document.all && !document.getElementById) {
        return document.all[a];
    }else{
        return document.getElementById(a);
    }
}

function trim(str){
  return str.replace(/^\s*|\s*$/g,"");
}

// this function call from all pages (index,list,show) onpageload and 
// on change city to set area drop down text.
  function loadAreas(localityBox,city,buttontype,setAreaField)
   {
     var category = document.getElementById('prop_category').value;
     var listingType;
     
     listingType = document.getElementById('listing_type').value;

     //Load areas only when listing type transition is from rent to other 3 or vice versa.
     //Apply this logic only when listing_type changes.
     if(old_listing_type != listingType &&
     (old_listing_type == 'sale' || old_listing_type == 'new' || old_listing_type == 'resale') &&
        (listingType == 'sale' || listingType == 'new' || listingType == 'resale')) {
        old_listing_type = listingType;
        return;
     }
     
     old_listing_type = listingType;     
     
     var city = document.getElementById(city).value;
      new Ajax.Request('/listing/searchArea/'+category+'/'+listingType+'/'+city, 
      { 
       method: 'get',
        
       onSuccess: function(transport) {
         var response = transport.responseText;
         locations = response.split(',');         
         setAreaDropDown(localityBox,setAreaField);
         },
       
       onFailure: function() { 
         bObject(localityBox).value = ready; },
       
       onLoading: function(){         
         }
      }
      );
    }
    
  // this function call from all pages (index,list,show,loadListProperty) "onclick"  event on
  //  area drop down text.
  function clearTextBox(localityBox)
   {
     if(bObject(localityBox).value== ready || bObject(localityBox).value == wait )
     {
       bObject(localityBox).value = "";
     }
   }
// this function call from all pages (index,list,show) onpageload 
// to set area drop down text.    
   function setAreaDropDown(localityBox,setAreaField)
  {
  	if(setAreaField == "0" || document.getElementById(setAreaField).value=='' || document.getElementById(setAreaField).value == 'none' || document.getElementById(setAreaField).value == null)
  	{
  		document.getElementById(localityBox).value =ready;
  	}
  	else
  	{
  		document.getElementById(localityBox).value =document.getElementById(setAreaField).value ;    		
  	}
      
    //This variable maintains listing_type value. Need it to determine whether AJAX call for areas to be fired or not.
    //The call is made only when transition is made from rent to rest 3 values and vice versa
    //This initializes the variable to its current value.
    //Do this only if the listing_type dropdown exists on the page.
    if(document.getElementById('listing_type') != null)
      old_listing_type = document.getElementById('listing_type').value;
  }
  
  /** this function call from loadListProperty onpageload and   *
   * on change city to set area drop down text. 
   * localityBox - text fielf where text will set ( ready, loading)
   * city - onchange selected city 
   * y  - if y=='0' then city will take from textbox id else direct pass city. 
   * area  - if area is not =='' then set in locality box
   * arealisttype - which type of event_city selected ( valuation, search, newlistProperty, resalelistproperty, searcherrequirment) 
   */

  function loadAreasForlistLoadProperty(localityBox,city,y,area,arealisttype)  
   {	//alert("desfdsf");
   	if(y=='0')
    {
      var city = document.getElementById(city).value; 
    }
    else
    {
    	 var city =city;
    }  
            //alert('show_location.php?city_id='+city);
			new Ajax.Request('show_location.php?city_id='+city, 
      { 
       method: 'get',
        
       onSuccess: function(transport) {       	
         var response = transport.responseText;
		 //alert('show_location.php?city_id='+city);
		 //alert(response);
         if(arealisttype=='listproperty')
         {
         	 loadlistlocations = response.split(',');         	         	
         }
         else if(arealisttype=='resalelocations')
         {         	          
           resalelocations = response.split(',');
          
         }else if(arealisttype=='searcher')
         {    	
           searcherlocations = response.split(',');
         }        
         else {                     
          loadlistlocations = resalelocations = searcherlocations = response.split(',');
         }         
         
         if(area==""){
         	document.getElementById(localityBox).value = ready;
         }else
         {
         	document.getElementById(localityBox).value = area;
         	}         
       },
       //alert(resalelocations);
       onFailure: function() { 
         bObject(localityBox).value = ready; 
       },
       
       onLoading: function(){
       }
      }
      );
    }
    
    // this function call on loadListProperty onpageload and on change of city to set state text.
    function loadStateForLoadListProperty(stateBox,city,x)
    {
    	if(stateBox!='')
    	{
	       if(x == '0')
	       {
	         var city = document.getElementById(city).value;
	       }
	       else
	       {
	         var city = city;
	       }
	         new Ajax.Request('/listing/getState?city='+ city,
	         {
	           method: 'get',
	        
	          onSuccess: function(transport) {
	          var response = transport.responseText;
	          document.getElementById(stateBox).value = response; 
	         },
	       
	         onFailure: function() {   
	       },
	       
	       onLoading: function(){
	       }
	      }
	      );
    	}             
    }     
    
//function to check enter key pressed on property valuation section on home page    
function enter_pressed(e){
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return false;
  return (keycode == 13);
}  

//This function will be used to load areas in home valuation and valuation page
function loadAreasForValuation(localityBox,city,y,area)  
{   
  if(y==0)
  {
    var city = document.getElementById(city).value;
  }      
  new Ajax.Request('/home/getAreaFromValuation/'+city,
  { 
     method: 'get',    
     onSuccess: function(transport) {  
   	 var response = transport.responseText;        
     valuationlocations = response.split(',');         
	 if(area==""||area==null){	     	
	     	document.getElementById(localityBox).value = ready;
	     }else
	     {
	     	document.getElementById(localityBox).value = area;
	     	}         
	   },   
     onFailure: function() { 
     bObject(localityBox).value = ready; 
   },   
   onLoading: function(){
   }
  }
  );
}  