/**
 * Function switchStaff
 * @param {int} staffId
 * @param {int} staffTotal
 * @return void
 */
function switchStaff(staffId,staffTotal) {
							
	// Switch off all staff members
	for (var counter=1; counter<=staffTotal; counter++) {				
		$('#switch_'+counter).attr('class','');
		$('#staff_'+counter).css('display','none');
	}
	// Switch selected staff member on
	$('#switch_'+staffId).attr('class','selected');
	$('#staff_'+staffId).css('display','');
}

/**
 * LIVE-UPDATER
 * based on jquery
 */

/*
 * AutoComplete
 */

var isSafari = false,isMoz = false, isIE = false;

jQuery.each(jQuery.browser, function(i, val) {	
    if(i == 'safari'){
		isSafari = val;	
	}if(i == 'msie'){
		isIE = val;	
	}if(i == 'mozilla'){
		isMoz = val;	
	}		
});

/**
 * Function liveUpdater
 * @param {Object} uriFunc
 * @param {Object} postFunc
 * @param {Object} preFunc
 * @return void
 */    
function liveUpdater(uriFunc, postFunc, preFunc)
{
  if(!postFunc) postFunc = function () {};
  if(!preFunc) preFunc = function () {};

  return createLiveUpdaterFunction(uriFunc, postFunc, preFunc);
}

/**
 * Function recreateTR
 * @param {Object} parentElement
 * @param {Object} subtree
 */
function recreateTR(parentElement, subtree)
{
  for(var i = parentElement.childNodes.length-1; i>=0; i--)
  {
    parentElement.removeChild(parentElement.childNodes[i]);
  }

  for(var i=0; i<subtree.childNodes.length; i++)
  {
    var cell = document.createElement(subtree.childNodes[i].nodeName);
    cell.innerHTML = flattenChildren(subtree.childNodes[i].childNodes)
    parentElement.appendChild(cell);
  }
}

/**
 * Function createLiveUpdaterFunction
 * @param {Object} uriFunc
 * @param {Object} postFunc
 * @param {Object} preFunc
 */
function createLiveUpdaterFunction(uriFunc, postFunc, preFunc)
{
    var request = false;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    }
    
    function update()
    {
        if(request && request.readyState < 4)
            request.abort();

            
        if(!window.XMLHttpRequest)
            request = new ActiveXObject("Microsoft.XMLHTTP");

        preFunc();
        request.onreadystatechange = processRequestChange;
        request.open("GET", uriFunc());
        request.send(null);
        return true;
    }

    function processRequestChange()
    {
      if(request.readyState == 4)
      {
        var xmlDoc = request.responseXML

        var body = xmlDoc.getElementsByTagName("body");

        if(body.length>0)
        {
          var nodes = body[0].childNodes
          for(var i=0;i<nodes.length;i++)
          {
            if(nodes[i].nodeType==1 && nodes[i].getAttribute("id")!=null)
            {
              var id = nodes[i].getAttribute("id")
              if(isIE && nodes[i].nodeName == 'tr')
              {
                recreateTR(document.getElementById(id), nodes[i]);
              }
              else
              {
                document.getElementById(id).innerHTML = flattenChildren(nodes[i].childNodes)
              }
            }
          }
        }

        var scripts = xmlDoc.getElementsByTagName("script");
        for(var i=0;i<scripts.length;i++)
        {
          if(scripts[i].firstChild!=null)
          {
            var script = scripts[i].firstChild.nodeValue
            if(script != null)
            {
              eval(script)
            }
          }
        }
        postFunc();
      }
    }

    return update;
}

/**
 * Function autocomplete
 * @param {Object} id
 * @param {Object} popupId
 * @param {Object} uri
 * @return void
 */
function autocomplete(id, popupId, uri)
{   	
    var inputField = document.getElementById(id);
    var popup = document.getElementById(popupId);
    var options = new Array(); 
    var current = 0;
    var originalPopupTop = popup.offsetTop;	     
    function constructUri()
    {        
		var separator = "?";
        if(uri.indexOf("?") >= 0)
            separator = "&";
		var result = "";	
			result = uri + separator + "quotenumber=" + escape(inputField.value);														
        return result;
    }
   
    function hidePopup()
    {
      popup.style.visibility = 'hidden';
    }

    function handlePopupOver()
    {
      removeListener(inputField, 'blur', hidePopup);
    }
    
    function handlePopupOut()
    {
      if(popup.style.visibility == 'visible')
      {
        addListener(inputField, 'blur', hidePopup);
      }
    }
    
    function handleClick(e)
    {
	  inputField.value = eventElement(e).innerHTML;
	  
	  var href = '/';
	  	  	  					 	   		
	  if(typeof($(eventElement(e)).attr('importCarId')) != 'undefined' 
	  					&& typeof($(eventElement(e)).attr('carId')) != 'undefined')	
	  {										  					
	  					var str = ($(eventElement(e)).attr('importCarModelExtra')).replace(/\+/g,'-');
	  					str = str.replace(/\s/g,'');
	  					href += $(eventElement(e)).attr('importCarAccreditationName')+'/'+$(eventElement(e)).attr('importCarManufacturerName')+'/'+$(eventElement(e)).attr('importCarModelGroupName')+'/'+$(eventElement(e)).attr('importCarManufacturerName')+'-'+str+'/car/'+$(eventElement(e)).attr('importCarId')+'/'+$(eventElement(e)).attr('carId');
	  }					
	  				
	  if(typeof($(eventElement(e)).attr('importCarId')) == 'undefined' 
	  					&& typeof($(eventElement(e)).attr('carId')) != 'undefined')
	  {					
	  					var str = ($(eventElement(e)).attr('carModelExtra')).replace(/\+/g,'-');
	  					str = str.replace(/\s/g,'');
	  					href += $(eventElement(e)).attr('carAccreditationName')+'/'+$(eventElement(e)).attr('carManufacturerName')+'/'+$(eventElement(e)).attr('carModelGroupName')+'/'+$(eventElement(e)).attr('carManufacturerName')+'-'+str+'/car/'+$(eventElement(e)).attr('carId');
	  }					
	  	  			  	 				      	  
	  if(href != '/') $('#searchDirect').attr('action',href);
	  popup.style.visibility = 'hidden';
      inputField.focus();
    }
    
    function handleOver(e)
    {
      options[current].className = '';
      current = eventElement(e).index;
      options[current].className = 'selected';
    }
    
    function post()
    {
        current = 0;
        options = popup.getElementsByTagName("li");
        if((options.length > 1)
           || (options.length == 1 
               && options[0].innerHTML != inputField.value))
        {
          setPopupStyles();
		  // popup.style.visibility = 'visible';
          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 setPopupStyles()
    {
      var maxHeight
      if(isIE)
      {
        maxHeight = 200;
        //popup.style.left = '0px';
        //popup.style.top = (originalPopupTop + inputField.offsetHeight) + 'px';
      }
      else
      {
        maxHeight = window.outerHeight/3;
      }
      if(popup.offsetHeight < maxHeight)
      {
        popup.style.overflow = 'hidden';
      }
      else if(isMoz)
      {
        popup.style.maxHeight = maxHeight + 'px';
        popup.style.overflow = '-moz-scrollbars-vertical';
      }
      else
      {
        popup.style.height = maxHeight + 'px';
        popup.style.overflowY = 'auto';
      }
      popup.scrollTop = 0;
      popup.style.visibility = 'visible';
    }
    
    function addOptionHandlers(option)
    {
      addListener(option, "click", handleClick);
      addListener(option, "mouseover", handleOver);
    }
    
    var updater = liveUpdater(constructUri, post);
    var timeout = false;
   
    function start(e) {
	   	
      if (timeout)
        window.clearTimeout(timeout);
      //up arrow
      if(e.keyCode == 38)
      {
        if(current > 0)
        {
          options[current].className = '';
          current--;
          options[current].className = 'selected';
          options[current].scrollIntoView(false);
        }
      }
      //down arrow
      else if(e.keyCode == 40)
      {
        if(current < options.length - 1)
        {
          options[current].className = '';
          current++;
          options[current].className = 'selected';
          options[current].scrollIntoView(false);
        }
      }
      //enter or tab
      else if((e.keyCode == 13 || e.keyCode == 9) && popup.style.visibility == 'visible')
      {        		 
	  	inputField.value = options[current].innerHTML;	  	
	  	var href = '/';
		
		
	  						
	  	if(typeof($(options[current]).attr('importCarId')) != 'undefined' && typeof($(options[current]).attr('carId')) != 'undefined')
	  	{
	  				var str = ($(options[current]).attr('importCarModelExtra')).replace(/\+/g,'-');
	  					str = str.replace(/\s/g,'');
	  				href += $(options[current]).attr('importCarAccreditationName')+'/'+$(options[current]).attr('importCarManufacturerName')+'/'+$(options[current]).attr('importCarModelGroupName')+'/'+$(options[current]).attr('importCarManufacturerName')+'-'+str+'/car/'+$(options[current]).attr('importCarId')+'/'+$(options[current]).attr('carId');
	  	}				  					  	
		if(typeof($(options[current]).attr('importCarId')) == 'undefined' && typeof($(options[current]).attr('carId')) != 'undefined')
		{
	  				var str = ($(options[current]).attr('carModelExtra')).replace(/\+/g,'-');
	  				str = str.replace(/\s/g,'');
	  				href += $(options[current]).attr('carAccreditationName')+'/'+$(options[current]).attr('carManufacturerName')+'/'+$(options[current]).attr('carModelGroupName')+'/'+$(options[current]).attr('carManufacturerName')+'-'+str+'/car/'+$(options[current]).attr('carId');
	  	}			
      	  	
	  	
		if(href != '/') $('#searchDirect').attr('action',href);
	        						
        popup.style.visibility = 'hidden';
        inputField.focus();
        if(isIE)
        {
          event.returnValue = false;
        }
        else
        {
          e.preventDefault();
        }
      }
      else
      {
        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(isMoz)
  {
	return event.currentTarget;
  }
  else
  {
    return event.srcElement;
  }
}

function addKeyListener(element, listener)
{
  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(element.addEventListener)
  {
    element.addEventListener(type, listener, false);
  }
  else
  {
    element.attachEvent('on' + type, listener);
  }
}

function removeListener(element, type, listener)
{
  if(element.removeEventListener)
  {
    element.removeEventListener(type, listener, false);
  }
  else
  {
    element.detachEvent('on' + type, listener);
  }
}

/**
 * XML Helper functions
 * @param {Object} node
 */
function flatten(node)
{
	if(node.nodeType == 1)
	{
		return '<' + node.nodeName + flattenAttributes(node) + '>' +
		flattenChildren(node.childNodes) + '</' + node.nodeName + '>';
	}
	else if(node.nodeType == 3)
	{
		return node.nodeValue;
	}
}
/**
 * Function flattenAttributes
 * @param {Object} node
 * @return buffer
 */
function flattenAttributes(node)
{
  var buffer = ''
  for(var i=0;i<node.attributes.length;i++)
  {
    var attribute = node.attributes[i]
    buffer += ' '+attribute.name+'="'+attribute.value+'"'
  }
  return buffer;
}

/**
 * Function flattenChildren
 * @param {Object} nodes
 * @return buffer
 */
function flattenChildren(nodes)
{
	var buffer = '';
	if(nodes.length > 0)
	{
		for (var i=0;i<nodes.length;i++)
		{
			buffer += flatten(nodes[i]);
		}
	}
	return buffer;
}
