﻿
/* VARIABLES */

var blurCount   = 0;
var locationInput;
var locationTypeInput;
var locationCombo;
var locationComboPanel;
var textInput;
var autoCompleteTimer;
var autoCompleteKeyCode;

/* METHODS */

// Calls the JS handler with the partial string to match 

function AutoCompleteTextInputChangeHandler(
  e, 
  locationInputID, 
  locationTypeInputID, 
  locationComboID, 
  textInputID, 
  propositionInputID, 
  serviceUrl,
  divElementID) {
  
  var keyCode;
  
    
  if (autoCompleteTimer){
    clearTimeout(autoCompleteTimer);
  }
    
  if(!e) {
    e=window.event;
  }
  
  keyCode = e.keyCode ? e.keyCode : e.which;
  matchStr = $(textInputID).value;
  if(matchStr.length <3)
  {
     AutoCompleteHideOptionList($(locationComboID), divElementID);
     return;
  }      
  autoCompleteTimer = setTimeout("ProcessAutoCompleteTextInput('" + keyCode + "', '" + locationInputID + "','" + locationTypeInputID + "','" + locationComboID + "','" + textInputID + "','" + propositionInputID + "','" + serviceUrl + "','" + divElementID + "',true);",250);
        
}

function ProcessAutoCompleteTextInput(
    e, 
    locationInputID, 
    locationTypeInputID, 
    locationComboID, 
    textInputID, 
    propositionInputID, 
    serviceUrl,
    divElementID,
    typeAhead) {
  
  var obj;
  var propositionGuid     = '';
  var matchStr;
  locationInput           = $(locationInputID);
  locationTypeInput   = $(locationTypeInputID);
  locationCombo           = $(locationComboID);
  locationComboPanel  = $(divElementID);
  textInput = $(textInputID);
    
  
  //locationInput.value = '';
  //locationTypeInput.value = '';
  
  iKeyCode = e;
  
  
  if(iKeyCode == 40){
  
    if(locationCombo.style.display == "none"){
        locationComboPanel.style.display = 'block';
        locationCombo.style.display = 'block';
    }
    if(locationCombo.options.length > 0){
        locationCombo.focus();
        locationCombo.selectedIndex = 2;
    }
    
    if(locationCombo.value != "0000-0000-0000-0000") {                        
        locationInput.value = locationCombo.value.split('_')[0];
        locationTypeInput.value = locationCombo.value.split('_')[1];
        
    } else {                     
        locationInput.value = '';
        locationTypeInput.value = '';
    }    
    
    return;    
  }
  
  if(iKeyCode == 13){
    locationComboPanel.style.display = 'none';
    locationCombo.style.display = 'none';
    if(locationCombo.value != "0000-0000-0000-0000") {                        
        locationInput.value = locationCombo.value.split('_')[0];
        locationTypeInput.value = locationCombo.value.split('_')[1];
        
    } else {                     
        locationInput.value = '';
        locationTypeInput.value = '';
    }    
    
    return;
  }
  
  if ((iKeyCode < 32 && iKeyCode != 16) || (iKeyCode >= 33 && iKeyCode <= 46 && iKeyCode != 40) || (iKeyCode >= 112 && iKeyCode <= 123)){    
    return;    
  }
  
  propositionGuid = $(propositionInputID).value;
  matchStr = $(textInputID).value;
  
  if(matchStr.length >=3){
    LoadOptionsIntoLocationControl(siteRoot + serviceUrl + '&proposition_guid=' + propositionGuid + '&match=' + matchStr, locationInputID, locationTypeInputID, locationComboID, divElementID, textInputID, matchStr, typeAhead);
  } 

}

// Calls the AJAX handler and populates the dropdown with the returned formatted HTML
function LoadOptionsIntoLocationControl( 
    ajaxHandlerUri, 
    locationInputID, 
    locationTypeInputID,
    locationComboID,
    divElementID,
    textInputID,
    matchString,
    typeAhead){

  locationInput       = $(locationInputID);
  locationTypeInput   = $(locationTypeInputID);
  locationCombo       = $(locationComboID);
  locationComboPanel  = $(divElementID);
  var xmlHttp             = CreateXmlHttp();
  var matchFound          = false;
  var index               = 0;
    
    if(locationCombo){
    
    /*
      if(locationCombo.options.length > 0){
       
        for(index = 0; index < locationCombo.options.length; index++){
          
          if(locationCombo.options[index].innerHTML.toLowerCase().indexOf(matchString.toLowerCase()) == 0){
            matchFound = true;   
                             
          } else if(locationCombo.options[index].value != '0000-0000-0000-0000'){
            locationCombo.options[index] = null;                   
            index--;
          }
              
        }
            
        if(matchFound){
          var offsetIndex = 0;
          locationCombo = $(locationComboID); // fixes an IE bug
          locationComboPanel.style.display = 'block';
          locationCombo.style.display = 'block';
          
          if(locationCombo.options[0].value == '0000-0000-0000-0000'){
            offsetIndex = 1;
          }
          else{
            offsetIndex = 0;
          }
          
          if(typeof(typeAhead) != 'undefined'){
            if(typeAhead == true){
                AutoCompleteTextBoxTypeAhead(locationCombo.options[offsetIndex].text, textInputID);
            }
          }          
          locationCombo.selectedIndex = offsetIndex;
          
          locationInput.value = locationCombo.value;            
        }

    }
      
      */

	    if(!matchFound){
	        if(xmlHttp){

            try{                
                  
              xmlHttp.onreadystatechange = function() { 
                if (xmlHttp.readyState==4){                    
                    if (xmlHttp.status==200)
                        updateTextField(xmlHttp, 
                            locationInputID, 
                            locationTypeInputID,
                            locationComboID,
                            divElementID,
                            textInputID,
                            matchString,
                            typeAhead);
                }
              }                
              xmlHttp.open("GET", ajaxHandlerUri,  true);
              xmlHttp.send(null);              
                                
            }catch(e){
              alert(e);
            }

	      }else{
          alert('Failed to create XmlHttp object to make request to <' + ajaxHandlerUri + '!');
        }
    }
  /*  var optionCount = locationCombo.options.length;
    if(optionCount <= 6){
        locationComboPanel.style.display = 'none';
        locationComboPanel.style.height = ((optionCount+1)*12) + "px";
        locationCombo.setAttribute("size",optionCount);              
        locationComboPanel.style.display = 'block';
    }
    else{
        locationComboPanel.style.display = 'none';
        locationComboPanel.style.height = "auto";
        locationCombo.setAttribute("size","7");              
        locationComboPanel.style.display = 'block';
    }*/
    
  }else{
    alert('Cannot find element with an id of <' + elementId + '>!');
  }

}

function updateTextField(xmlHttp, 
    locationInputID, 
    locationTypeInputID,
    locationComboID,
    divElementID,
    textInputID,
    matchString,
    typeAhead){
    var locationComboID = locationCombo.id;
    if (browserType.indexOf('IE') >= 0){
        locationCombo.innerHTML = '<option>No matches found</option>' + xmlHttp.responseText;
        if (xmlHttp.responseText.length == 0) {
            locationCombo.innerHTML += "<option value='0000-0000-0000-0000'>No matches found</option>";
        }
        locationCombo.outerHTML = locationCombo.outerHTML; // fixes a IE bug
        purge(locationCombo); // fixes IE memory leaks caused by setting outerHTML
          
      }else{
        locationCombo.innerHTML = xmlHttp.responseText;
      }
//      if (xmlHttp.responseText.length > 0){       
       
        locationComboPanel.style.display = 'block'; 
        locationCombo.style.display = 'block';
        locationCombo.style.height = 'auto';
                          
        if (navigator.userAgent.indexOf("Firefox")!= -1){
          locationCombo.style.top = "17px;"   
          locationCombo.style.left = "-130px;" 
        }
        
        locationCombo = $(locationComboID); // fixes an IE bug
        
        if(typeof(typeAhead) != 'undefined'){
            if(typeAhead == true){
               // AutoCompleteTextBoxTypeAhead(locationCombo.options[1].text,textInputID);
                locationComboPanel.style.display = 'block'; 
                locationCombo.style.display = 'block';
                locationCombo.style.height = 'auto';
            }
        }
        
         locationCombo.selectedIndex = 1;
         locationInput.value = locationCombo.value;
        
        if(locationCombo.value != "0000-0000-0000-0000"){                        
          locationInput.value = locationCombo.value.split('_')[0];
          locationTypeInput.value = locationCombo.value.split('_')[1];
            
        }else{                     
          locationInput.value = '';
          locationTypeInput.value = '';
        }
//          
//      }else{        
//        locationComboPanel.style.display = 'none';
//        locationComboPanel.style.height = '0px';
//        locationCombo.style.display = 'none';        
//      }

      xmlHttp = null;
}

var startsWithThreeLetterCodeRegex = new RegExp("^[A-Z][A-Z][A-Z] .*");

function AutoCompleteTextBoxTypeAhead(sSuggestion /*:string*/, textInputID)
{
    var input = $(textInputID);
    var iLen = input.value.length;
    var inputValueUpper = input.value.toUpperCase();
    var suggestionUpper = sSuggestion.toUpperCase();
    var airportCodeMatch = suggestionUpper.match(startsWithThreeLetterCodeRegex)

    if (input.createTextRange || input.setSelectionRange) 
    {
        if (input.value.toUpperCase() == suggestionUpper.substring(0, input.value.length))
        {
            input.value = sSuggestion;
            AutoCompleteTextBoxSelectRange(iLen, sSuggestion.length, textInputID);
        }
        else if (airportCodeMatch != null && input.value.toUpperCase() == suggestionUpper.substring(4, iLen + 4))
        {
            input.value = sSuggestion.substring(4, sSuggestion.length);
            AutoCompleteTextBoxSelectRange(iLen, sSuggestion.length, textInputID);
        }
    }
}

function AutoCompleteTextBoxSelectRange(iStart /*:int*/, iLength /*:int*/, textInputID){

    var input = $(textInputID);
    var oRange;
    
    //use text ranges for Internet Explorer
    if (input.createTextRange){
        oRange = input.createTextRange(); 
        oRange.moveStart("character", 0); 
        oRange.moveEnd("character", 0);      
        oRange.select();
       
    //use setSelectionRange() for Mozilla
    } else if (input.setSelectionRange){
        input.setSelectionRange(0, 0);
    }     
    
    //set focus back to the textbox
    input.focus();
}

function SetSelectionRange(input, selectionStart, selectionEnd){

  var range;
  
  if (input.setSelectionRange){
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);     
             
  } else if (input.createTextRange) {

        range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();          
  }
  
}

function AutoCompleteOptionListChangeHandler(input, textInputID, locationInputID, locationTypeInputID){

  var locationTextInput       = $(textInputID);
  var locationInput           = $(locationInputID);
  var locationTypeInput   = $(locationTypeInputID);

  if(input.value != "0000-0000-0000-0000"){  
    locationTextInput.value     = input.options[input.selectedIndex].text;
    locationInput.value         = input.value.split('_')[0];
    locationTypeInput.value = input.value.split('_')[1];
      
  }else{
    locationTextInput.value = '';
    locationInput.value = '';
    locationTypeInput.value = '';
  }
    
}

function SetNextFocus(obj){

    var form = obj.form;
    var elements = form.elements;
    var x, nextEl;

    for (var i=0, len=elements.length; i<len; i++) {
    
        x = elements[i];
        
        if (obj == x) {
        
            nextEl = elements[i+1];
            
            if (nextEl.focus){
            
                try { 
                    nextEl.focus();
                } catch(e){
                    i++; //this one don't work. Try the next element
                }
                
                obj.onblur = null;                
                return false;
            }            
        }        
    }    
}

function AutoCompleteOptionListKeyUpHandler(e, locationCombo){


  if(!e) 
    e=window.event;
  
  iKeyCode = e.keyCode ? e.keyCode : e.which;
  
  if(iKeyCode == 13) {
    AutoCompleteOptionListChangeHandler(locationCombo, textInput.id, locationInput.id, locationTypeInput.id);
    AutoCompleteHideOptionList(locationCombo,locationComboPanel.id);
  }

}

function AutoCompleteOptionListClickHandler(e, locationCombo, divElementID){

    textInput.value = locationCombo.options[locationCombo.selectedIndex].text;
    SetSelectionRange(textInput,0,0);
    if(locationCombo.value != "0000-0000-0000-0000") {                        
        locationInput.value = locationCombo.value.split('_')[0];
        locationTypeInput.value = locationCombo.value.split('_')[1];
        
    } else {                     
        locationInput.value = '';
        locationTypeInput.value = '';
        textInput.value = "";
    }
    AutoCompleteHideOptionList(locationCombo, divElementID);

}

function AutoCompleteHideOptionList(locationCombo, divElementID){

  var locationComboPanel      = $(divElementID);
  if(locationCombo.style.display == 'none') return;  
  if(blurCount > 0 && locationComboPanel.style.display != 'none' && locationCombo.style.display != 'none'){      
      locationComboPanel.style.display = 'none';
      locationComboPanel.style.height = '0px';
      locationCombo.style.display = 'none';
  }
  
  blurCount++;  
}

function AutoCompleteTextInputClickEventHandler(){
    blurCount++;
}

function purge(d){    
    var a = d.attributes, i, l, n;    
    if (a) {        
        l = a.length;        
        for (i = 0; i < l; i += 1) {            
            n = a[i].name;            
            if (typeof d[n] === 'function') {                
                d[n] = null;            
            }        
        }    
    }    
    a = d.childNodes;    
    if (a) {        
        l = a.length;        
        for (i = 0; i < l; i += 1) {            
            purge(d.childNodes[i]);        
        }    
   }
}

function checkHiddenValues(input,textInputID){
    var locationTextInput       = $(textInputID);
    if(locationTextInput.value == ""){
        input.value = "";    
    }
}
