var IS_DEBUG = false;

if(IS_DEBUG) alert("inizio");
if (navigator.userAgent.indexOf("Safari") > 0)
{
  if(IS_DEBUG) alert("safari");
  isSafari = true;
  isMoz = false;
  isIE = false;
}
else if (navigator.product == "Gecko")
{
  if(IS_DEBUG) alert("Moz");
  isSafari = false;
  isMoz = true;
  isIE = false;
}
else
{
  if(IS_DEBUG) alert("IE");
  isSafari = false;
  isMoz = false;
  isIE = true;
}
var inputField = null;
var inputFieldValue = null;
var popup = null;
var httpReq = false;
var maxHeight = 80;
var servletSoa = "";

function liveUpdater(uriFunc, postFunc, preFunc)
{
  //if(IS_DEBUG) alert("liveUpdater");
  if(!postFunc) postFunc = function () {};
  if(!preFunc) preFunc = function () {};

  return createLiveUpdaterFunction(uriFunc, postFunc, preFunc);
}

function createLiveUpdaterFunction(uriFunc, postFunc, preFunc)
{
  //if(IS_DEBUG) alert("createLiveUpdaterFunction");
  
  init();
	
	function init() {
		if(IS_DEBUG) alert("init()");
	  if (window.ActiveXObject) {
    // Internet Explorer
	  // Instantiate the latest MS ActiveX Objects
		if (_XML_ActiveX) {
		  httpReq = new ActiveXObject(_XML_ActiveX);
    } else {
      // loops through the various versions of XMLHTTP in IE, in order of how common they are
			var versions = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP", "Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0",
			                "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0"];
			for (var i = 0; i < versions.length ; i++) {
			  try {
			    // Try and  create the ActiveXObject for Internet Explorer, 
					// if it doesn't work  switch to next version and check again.
					httpReq = new ActiveXObject(versions[i]);
					if (httpReq) {
					  var _XML_ActiveX = versions[i];
						break;
					}
			  }
				catch (e) {
				  // TRAP
				} ;
			};
		}
	}
	// Well if there is no ActiveXObject available it must be firefox, opera, or something else
	if (!httpReq && typeof XMLHttpRequest != 'undefined') {
	  try {
	    httpReq = new XMLHttpRequest();
		} catch (e) {
			httpReq = false;
		}
	}
	}
   
    function update()
    {
      init();
      if(IS_DEBUG) alert("update -> caratteri inseriti: "+inputField.value.length);
      if (inputField.value.length < 2) {
        //pulisco popup
        popup.innerHTML = "";
        popup.style.visibility = 'hidden';
        inputField.focus();
        return false;
      }

      if(IS_DEBUG) alert("update() "+httpReq.readyState);
      if(IS_DEBUG) alert("uriFunc() " + uriFunc());
      /*if(httpReq && httpReq.readyState < 4)
      {
        httpReq.abort();
      }*/
      
      //preFunc();
      httpReq.onreadystatechange = processRequestChange;

      httpReq.open("GET", uriFunc());
      httpReq.send(null);
      return true;
    }

    function processRequestChange()
    {
      //if(IS_DEBUG) alert("processRequestChange");
      //if(IS_DEBUG) alert("processRequestChange "+httpReq.readyState+" - "+httpReq.status);
      if(httpReq.readyState == 4){
        if(httpReq.status == 200){
          if (IS_DEBUG) alert("responseText: ["+httpReq.responseText+"]");
          //document.getElementById("autocomplete-popup").innerHTML = request.responseText;
          popup.innerHTML = httpReq.responseText;
          postFunc();
        } else {
					if (IS_DEBUG) alert(httpReq.status + " Error: Could not retrieve data from server. Contact Support");
				}
      }
    }

    return update;
}

// *****************************************************

function autocomplete(id, popupId, uri,id_value)
{
	
    if(IS_DEBUG) alert("autocomplete "+id_value+":"+id);
    
    inputField = document.getElementById(id);
    inputFieldValue = document.getElementById(id_value);
    popup = document.getElementById(popupId);
    var options = new Array(); 
    var current = 0;
    var originalPopupTop = popup.offsetTop; 
    
    function constructUri()
    {
    	  // if (IS_DEBUG) alert(id);
	  //alert ("servlet: " + document.getElementById("servlet").value);
	  //alert ("inputField.value: " + inputField.value);
	  //alert ("concat: " + document.getElementById("servlet").value + " + " + "&value=" + " + " +inputField.value);
    	  var uristr = document.getElementById("servlet").value + '&value=' + inputField.value; // + "&sizerange=" + inputField.value + "&site=" + document.getElementById("site").value + "&locale=" + document.getElementById("locale").value + "&vehicle_type=" + document.getElementById("vehicleType").value; 
        if(IS_DEBUG) alert("uri: "+uristr);
        return uristr;
    }
   
    function hidePopup()
    {
      // if(IS_DEBUG) alert("hidePopup");
      popup.style.visibility = 'hidden';
    }

    function handlePopupOver()
    {
      // if(IS_DEBUG) alert("handlePopupOver");
      removeListener(inputField, 'blur', hidePopup);
    }
    
    function handlePopupOut()
    {
      // if(IS_DEBUG) alert("handlePopupOut");
      if(popup.style.visibility == 'visible')
      {
        addListener(inputField, 'blur', hidePopup);
      }
    }
    
    function handleClick(e)
    {
      if(IS_DEBUG) alert("handleClick");
      //inputField.value = eventElement(e).innerHTML;
      inputField.value = eventElement(e).firstChild.nodeValue;
      inputFieldValue.value = inputField.value;
      popup.style.visibility = 'hidden';
      inputField.focus();
    }
    
    function handleOver(e)
    {
      //if(IS_DEBUG) alert("handleOver");
      options[current].className = '';
      current = eventElement(e).index;
      options[current].className = 'selected';
    }
    
    function post()
    {
      if(IS_DEBUG) alert("post");
        current = 0;
        options = popup.getElementsByTagName("li");
        if((options.length > 1)
           || (options.length == 1 
               && options[0].innerHTML != inputField.value))
        {
          setPopupStyles();
          for(var i = 0; i < options.length; i++)
          {
            options[i].index = i;
            addOptionHandlers(options[i]);
          }
          options[0].className = 'selected';
        }
        else
        {
          popup.style.visibility = 'hidden';
        }
    }
    
    function findPosX(obj)
	{
		var curleft = 0;
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curleft += obj.offsetLeft
				obj = obj.offsetParent;
			}
		}
		else if (obj.x)
			curleft += obj.x;
		
		if (IS_DEBUG) alert("Left position:" + curleft);	
		
		return curleft;
	}
	
	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 setPopupStyles()
    {
      if(IS_DEBUG) alert("setPopupStyles");
      //var maxHeight
      var popupHeight = maxHeight;
      if(IS_DEBUG) alert('popup.offsetHeight: '+popup.offsetHeight+' popup.clientHeight: '+popup.clientHeight);
      if(popup.offsetHeight < maxHeight)
      {
        popup.style.overflow = 'hidden';
        popupHeight = popup.offsetHeight;
      }
      else if(isMoz)
      {
        popup.style.maxHeight = maxHeight + 'px';
        popup.style.overflow = '-moz-scrollbars-vertical';
      }
      else
      {
        popup.style.height = maxHeight + 'px';
        popup.style.overflowY = 'auto';
      }
      if(isIE)
      {
        //maxHeight = 200;
        //maxHeight = 80;
        //popup.style.top = (findPosY(inputField)+ inputField.offsetHeight) + 'px';
        popup.style.top = findPosY(inputField) - popupHeight -4 + 'px';
        popup.style.left = (findPosX(inputField)) + 'px';
        if (IS_DEBUG) alert("TOP: ["+popup.style.left+"]["+popup.style.top+"]");
        popup.style.width='320px';
      }
      else
      {
        if(IS_DEBUG) alert(window.outerHeight/3);
        //maxHeight = window.outerHeight/3;
        //maxHeight = 80;
        popup.style.top = findPosY(inputField) - popupHeight -3 + 'px';
        popup.style.left = (findPosX(inputField)) + 'px';
        if (IS_DEBUG) alert("TOP: ["+popup.style.left+"]["+popup.style.top+"]");
        popup.style.width='320px';
      }
      popup.scrollTop = 0;
      popup.style.visibility = 'visible';
    }
    
    function addOptionHandlers(option)
    {
      // if(IS_DEBUG) alert("addOptionHandlers");
      addListener(option, "click", handleClick);
      addListener(option, "mouseover", handleOver);
    }
    
    var updater = liveUpdater(constructUri, post);
    var timeout = false;
   
    function start(e) {
      //if(IS_DEBUG) alert("start "+e.keyCode);
      //pulisco popup
      //popup.innerHTML = "";
      if(IS_DEBUG) alert("caratteri inseriti: "+inputField.value.length);
      if (timeout)
        window.clearTimeout(timeout);
      //up arrow
      if(e.keyCode == 38)
      {
      	//pulisco campo hidden
        inputFieldValue.value = "";
        if(current > 0)
        {
          options[current].className = '';
          current--;
          options[current].className = 'selected';
          options[current].scrollIntoView(true);
        }
      }
      //down arrow
      else if(e.keyCode == 40)
      {
      	//pulisco campo hidden
        inputFieldValue.value = "";
        if(current < options.length - 1)
        {
          options[current].className = '';
          current++;
          options[current].className = 'selected';
          options[current].scrollIntoView(true);
        }
      }
      //enter or tab
      //else if((e.keyCode == 13 || e.keyCode == 9) && popup.style.visibility == 'visible')
      else if (e.keyCode == 13) // || e.keyCode == 9)
      {
      	if(IS_DEBUG) alert("enter/tab");
        inputField.value = options[current].innerHTML;
        inputFieldValue.value = inputField.value;
        if(IS_DEBUG) alert("inputFieldValue "+inputFieldValue.value);
        popup.style.visibility = 'hidden';
        inputField.focus();
        if(isIE)
        {
          event.returnValue = false;
        }
        else
        {
          e.preventDefault();
        }
      }
      //shift or uppercase or ctrl or alt
      else if ((e.keyCode == 16 || e.keyCode == 20 || e.keyCode == 17 || e.keyCode == 18)) 
      {
        null;
      }
      else
      {
        if(IS_DEBUG) alert("else che chiama window.setTimeout...")
        //pulisco campo hidden
        inputFieldValue.value = "";
        timeout = window.setTimeout(updater, 300);
      }
    }
  addKeyListener(inputField, start);
  addListener(popup, 'mouseover', handlePopupOver);
  addListener(popup, 'mouseout', handlePopupOut);
}

// *****************************************************

/* Functions to handle browser incompatibilites */
function eventElement(event)
{
 // if (IS_DEBUG) alert("eventElement");
  if(isMoz)
  {
    return event.currentTarget;
  }
  else
  {
    return event.srcElement;
  }
}

function addKeyListener(element, listener)
{
  // if(IS_DEBUG) alert("addKeyListener");
  if (isSafari)
    element.addEventListener("keydown",listener,false);
  else if (isMoz)
    element.addEventListener("keypress",listener,false);
  else
    element.attachEvent("onkeydown",listener);
}

function addListener(element, type, listener)
{
  // if(IS_DEBUG) alert("addListener");
  if(element.addEventListener)
  {
    element.addEventListener(type, listener, false);
  }
  else
  {
    element.attachEvent('on' + type, listener);
  }
}

function removeListener(element, type, listener)
{
  // if(IS_DEBUG) alert("removeListener");
  if(element.removeEventListener)
  {
    element.removeEventListener(type, listener, false);
  }
  else
  {
    element.detachEvent('on' + type, listener);
  }
}

function checkSubmit(id)
{
	if(IS_DEBUG) alert("1" + inputFieldValue.value);
	if(IS_DEBUG) alert("2" + document.getElementById(id).value);
  if (httpReq) {
    if (document.getElementById(id).value.length == 0) {
      if (IS_DEBUG) alert("Select an item from the list");
      return false;
    }
    document.getElementById(id).value = 0;
  }
  else
  {
  	if (inputField.value.length < 2 ) 
  	{
  		if (IS_DEBUG) alert("Insert at least two characters");
  		return false;
  	}
  	document.getElementById(id).value = 1;
  }
  return true;
}

function checkSubmitPattern(string_error)
{
	
	if (document.getElementById("uri").value == "")
	{
		if (IS_DEBUG) alert(string_error);
     		return false;	
	}
	
	return true;
}

