var myProxy = new UAproxy();

function serverLookupShipState(thisCountry) {

	myProxy.setCallbackHandler(serverLookupShipStateSuccess);
	myProxy.lookupState(thisCountry);
}

function serverLookupShipStateSuccess(result) {

	AutoComplete_Create('ShipState', result);
}

function serverLookupBillState(thisCountry) {

	myProxy.setCallbackHandler(serverLookupBillStateSuccess);
	myProxy.lookupState(thisCountry);
}

function serverLookupBillStateSuccess(result) {

	AutoComplete_Create('BillState', result);
}

function serverCheckEmailAddress(thisAddress) {

	myProxy.setCallbackHandler(serverUsernameSuccess);
	myProxy.checkUsername(thisAddress);
}

function serverUsernameSuccess(result) {
	if (result == 'Found')
	{
		alert('I am sorry.<br/><br/>Your email address is found in our system.<br/><br/>Please login or enter a different<br/>email address.');
		document.getElementById('EmailAddress').value = '';
		document.formBilling('EmailAddress').value = '';
	}
}

function serverCheckShipState() {
	var stateInput = document.getElementById('ShipState').value;
	var countryInput = document.getElementById('ShipCountry').value;
	
	myProxy.setCallbackHandler(serverShipStateSuccess);
	myProxy.checkStateSpelling(stateInput,countryInput);
}

function serverShipStateSuccess(result) {
	if (result == 'InvalidInput')
	{
		if (document.getElementById('ShipCountry').value == 'US')
		{
			alert('The State is not valid for the<br/>Country of United States.<br/><br/>Please try again.<br/><br/>It may be necessary to choose your Country first so the State/Province<br/>is properly validated.');
		}
		else
		{
			if (document.getElementById('ShipCountry').value == 'CA')
			{
				alert('The Province is not valid for the<br/>Country of Canada.<br/><br/>Please try again.<br/><br/>It may be necessary to choose your Country first so the State/Province<br/>is properly validated.');
			}
			else
			{
				if (document.getElementById('ShipCountry').value == 'DE')
				{
					alert('The Province is not valid for the<br/>Country of Germany.<br/><br/>Please try again.<br/><br/>It may be necessary to choose your Country first so the State/Province<br/>is properly validated.');
				}
				else
				{
				alert('The State/Province is not valid for the Country.<br/><br/>Please try again.<br/><br/>It may be necessary to choose your Country first so the State/Province<br/>is properly validated.');
				}
			}
		}
		document.getElementById('ShipState').value = '';
		document.getElementById('ShipState').focus();
		return false;
	}
	else
	{
		document.getElementById('ShipState').value = result;
		return true;
	}
}

function serverCheckBillState() {
	var stateInput = document.getElementById('BillState').value;
	var countryInput = document.getElementById('BillCountry').value;
	
	myProxy.setCallbackHandler(serverBillStateSuccess);
	myProxy.checkStateSpelling(stateInput,countryInput);
}

function serverBillStateSuccess(result) {
	if (result == 'InvalidInput')
	{
		if (document.getElementById('BillCountry').value == 'US')
		{
			alert('The State is not valid for the<br/>Country of United States.<br/><br/>Please try again.<br/><br/>It may be necessary to choose your<br/>Country first so the State/Province<br/>is properly validated.');
		}
		else
		{
			if (document.getElementById('BillCountry').value == 'CA')
			{
				alert('The Province is not valid for the<br/>Country of Canada.<br/><br/>Please try again.<br/><br/>It may be necessary to choose your<br/>Country first so the State/Province<br/>is properly validated.');
			}
			else
			{
				if (document.getElementById('BillCountry').value == 'DE')
				{
					alert('The Province is not valid for the<br/>Country of Germany.<br/><br/>Please try again.<br/><br/>It may be necessary to choose your<br/>Country first so the State/Province<br/>is properly validated.');
				}
				else
				{
					alert('The State/Province is not valid for the Country.<br/><br/>Please try again.<br/><br/>It may be necessary to choose your<br/>Country first so the State/Province<br/>is properly validated.');
				}
			}
		}
		document.getElementById('BillState').value = '';
		document.getElementById('BillState').focus();
		return false;
	}
	else
	{
		document.getElementById('BillState').value = result;
		return true;
	}
}

function validateNewAccount() {
	var invalid = " "; 
	var minLength = 6; 
	var illegalChars = /\W/;
	var alertString = "";
	var returnBoolean = true;
	if (document.newCustomer.newPassword.value.length < minLength) {
		alertString = alertString + 'Your password must be at least<br/>' + minLength + ' characters long.<br/><br/>';
		document.newCustomer.confirmPassword.value = "";
		document.newCustomer.newPassword.value = "";
		document.newCustomer.newPassword.focus();
		returnBoolean = false;
	}
	if (document.newCustomer.newPassword.value.indexOf(invalid) > -1) {
		alertString = alertString + 'Spaces are not allowed in password.<br/><br/>';
		document.newCustomer.confirmPassword.value = "";
		document.newCustomer.newPassword.value = "";
		document.newCustomer.newPassword.focus();
		returnBoolean = false;
	}
	if (document.newCustomer.newPassword.value != document.newCustomer.confirmPassword.value) {
		alertString = alertString + 'You did not enter the same password twice.<br/><br/>';
		document.newCustomer.confirmPassword.value = "";
		document.newCustomer.newPassword.value = "";
		document.newCustomer.newPassword.focus();
		returnBoolean = false;
	}
	if (returnBoolean == false)
	{
		alert(alertString + 'Please try again.');
		return false;
	}
	else
	{
		var emailInput = document.newCustomer.EmailAddress.value;
		var passwordInput = document.newCustomer.newPassword.value;
		var questionInput = document.newCustomer.SecurityQuestion.value;
		var answerInput = document.newCustomer.SecurityAnswer.value;		

		document.newCustomer.EmailAddress.value = '';
		document.newCustomer.newPassword.value = '';
		document.newCustomer.confirmPassword.value = '';
		document.newCustomer.SecurityQuestion.value = '';
		document.newCustomer.SecurityAnswer.value = '';
		document.getElementById('MyUsername').value = emailInput;
		document.getElementById('MyPassword').value = passwordInput;
		
		myProxy.setCallbackHandler(serverNewCustomerSuccess);
		myProxy.addNewCustomer(emailInput,passwordInput,questionInput,answerInput);
		return false;
	}
}

function validateNewEmailAccount() {
	var newEmailInput = document.newEmail.newEmail.value;
	var confirmEmailInput = document.newEmail.confirmEmail.value;
	
	if(newEmailInput != confirmEmailInput)
	{
		document.newEmail.newEmail.value = "";
		document.newEmail.confirmEmail.value = "";
		document.newEmail.newEmail.focus();
		alert('Your new and confirm email addresses<br/>do not match.<br/><br/>Please try again.');
		return false;
	}
	else
	{
		return true;
	}

}

function validateCreateAccount() {
	var invalid = " ";
	var minLength = 6;
	var illegalChars = /\W/;
	var alertString = "";
	var returnBoolean = true;
	if (document.newCustomer.newPassword.value.length < minLength) {
		alertString = alertString + 'Your password must be at least<br/>' + minLength + ' characters long.<br/><br/>';
		document.newCustomer.confirmPassword.value = "";
		document.newCustomer.newPassword.value = "";
		document.newCustomer.newPassword.focus();
		returnBoolean = false;
	}
	if (document.newCustomer.newPassword.value.indexOf(invalid) > -1) {
		alertString = alertString + 'Spaces are not allowed in password.<br/><br/>';
		document.newCustomer.confirmPassword.value = "";
		document.newCustomer.newPassword.value = "";
		document.newCustomer.newPassword.focus();
		returnBoolean = false;
	}
	if (document.newCustomer.newPassword.value != document.newCustomer.confirmPassword.value) {
		alertString = alertString + 'You did not enter the same password twice.<br/><br/>';
		document.newCustomer.confirmPassword.value = "";
		document.newCustomer.newPassword.value = "";
		document.newCustomer.newPassword.focus();
		returnBoolean = false;
	}
	if (returnBoolean == false)
	{
		alert(alertString + 'Please try again.');
		return false;
	}
	else
	{
		return true;
	}
}

function cleanCreditCard()
{
	var thisCC = document.getElementById('CCNum').value;
	thisCC = thisCC.replace(/[^0-9]+/g,'');
	document.getElementById('CCNum').value = thisCC;
	
}

function validatePOBox()
{
	var checkPOBox = new RegExp("[pP]{1}[.]*[oO]{1}[.]*[ ]*[bB]{1}[oO]{1}[xX]{1}"); 
	var thisShip1 = document.formBilling.ShipAddress1.value;
	var thisShip2 = document.formBilling.ShipAddress2.value;
		
	if (thisShip1.match(checkPOBox) != null || thisShip2.match(checkPOBox) != null)
	{
		var answer = confirm("You have entered a Post Office Box for the shipping address. Your order will be mailed using USPS Priority. If you wish to ship using UPS or Fedex, you will need to enter a physical shipping address. Continue using the Post Office Box address?")
		if (answer)
		{
			document.formBilling.ShipPOBox.value = 1;
			return true;
		}
		else
		{
			document.formBilling.ShipPOBox.value = 0;
			return false;
		}
	}
	else
		return true;
}

function ckPOBox(strAddress)
{
	var checkPOBox = new RegExp("[pP]{1}[.]*[oO]{1}[.]*[ ]*[bB]{1}[oO]{1}[xX]{1}"); 
		
	if (strAddress.match(checkPOBox) != null)
		return true;
	else
		return false;
}

function serverNewCustomerSuccess(result) 
{
	if (result == 'Success')
	{
		alert('Welcome to the Iwan Ries Family!<br/><br/>You may now login using your<br/>email address and password.');
		return false;
	}
	else
	{
		alert('I am sorry.<br/><br/>The was an issue with the system that prevents from creating your new account.<br/><br/>Please try again.');
		return false;
	}
}

function setNotSameShip() 
{
	document.formBilling.ShipSame[1].checked = true;
}

function SetBillToShip(sVal) 
{
	if(sVal == 'Yes') {
		document.formBilling.ShipFirstName.value = document.formBilling.BillFirstName.value;
		document.formBilling.ShipLastName.value = document.formBilling.BillLastName.value;
		document.formBilling.ShipBusinessName.value = document.formBilling.BillBusinessName.value;
		document.formBilling.ShipAddress1.value = document.formBilling.BillAddress1.value;
		document.formBilling.ShipAddress2.value = document.formBilling.BillAddress2.value;
		document.formBilling.ShipCity.value = document.formBilling.BillCity.value;
		document.formBilling.ShipState.value = document.formBilling.BillState.value;
		document.formBilling.ShipZip.value = document.formBilling.BillZip.value;
		document.formBilling.ShipCountry.value = document.formBilling.BillCountry.value;
	}
	else
	{
		document.formBilling.ShipFirstName.value = "";
		document.formBilling.ShipFirstName.style.required = "Yes";
		document.formBilling.ShipLastName.value = "";
		document.formBilling.ShipBusinessName.value = "";
		document.formBilling.ShipAddress1.value = "";
		document.formBilling.ShipAddress2.value = "";
		document.formBilling.ShipCity.value = "";
		document.formBilling.ShipState.value = "";
		document.formBilling.ShipZip.value = "";
		document.formBilling.ShipCountry.value = document.formBilling.BillCountry.value;
		document.formBilling.ShipFirstName.focus();
	}
}

function submitform()
{
	if(document.form1.onsubmit())
		{
			document.form1.submit();
		}
}
function toggledetailsMouseOver(id) {
   var e = document.getElementById(id);
   e.style.display = 'block';
}
function toggledetailsMouseOut(id) {
   var e = document.getElementById(id);
   e.style.display = 'none';
}
function setShipAmount(thisMethod,thisCost) {
	document.getElementById('myShipMethod').value = thisMethod;	
	document.getElementById('myShipAmount').value = thisCost;
	document.getElementById('lblShipping').innerHTML = '$' + CurrencyFormatted(thisCost);
	var t = document.getElementById('CheckoutTotal').value;
	var tTotal = thisCost*1 + t*1;
	document.getElementById('lblTotal').innerHTML = '$' + CurrencyFormatted(tTotal);
}

function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

function checkShipSelected() {
	if (document.getElementById('myShipMethod').value == '')
	{
		alert('Please choose your shipping.');
		return false;
	}
	else
	{
		return true;
	}
}

function checkExpDate()
{
	var CCTodayDate = new Date();
	var CCTodayYear = CCTodayDate.getFullYear();
	var CCTodayMonth = CCTodayDate.getMonth();
	CCTodayMonth = CCTodayMonth + 1;
	var CCExpDateYear = document.form1.CCExpYear.value;
	var CCExpDateMonth = document.form1.CCExpMonth.value;
	CCExpDateMonth = stripZeros(CCExpDateMonth);
	
	if (CCTodayYear == CCExpDateYear)
	{
		if (CCExpDateMonth < CCTodayMonth)
		{
			alert('The expiration date has expired.<br/><br/>Please try again.');
			return false;
		}
		else
		{
			return true;
		}
	}
	else
	{
		return true;
	}
}
function Right(str, n)
{
      if (n <= 0)
          return "";
      else if (n > String(str).length)
          return str;
      else
   {
          var iLen = String(str).length;
          return String(str).substring(iLen, iLen - n);
      }
}
function Left(str, n)
{
   if (n <= 0)
         return "";
   else if (n > String(str).length)
         return str;
   else
         return String(str).substring(0,n);
}
function stripZeros(inputStr) {
	var result = inputStr
	while (result.substring(0,1) == "0") {
		result = result.substring(1,result.length)
	}
	return result
}

function samplerSelection(thisID,thisProduct) {
	var thisHidden = document.getElementById('hidden'+thisID);
	var thisIMG = document.getElementById('img'+thisID);
	var thisFour = 0;
	var thisSelectedProduct = '';
	
	if (thisHidden.value == '')
	{
		for (var i = 0; i < document.getElementById('samplerForm').elements.length; i++ ) {
			if ((document.getElementById('samplerForm').elements[i].type == 'hidden') && (document.getElementById('samplerForm').elements[i].name != 'YourChoiceSubmitted')) {
				if (document.getElementById('samplerForm').elements[i].value != '') {
					thisFour = thisFour + 1;
					if (thisFour == 1)
					{
						thisSelectedProduct = thisFour + ') ' + document.getElementById('samplerForm').elements[i].value;
					}
					else
					{
						thisSelectedProduct = thisSelectedProduct + '<br/> ' + thisFour + ') ' + document.getElementById('samplerForm').elements[i].value;
					}
				}
			}
		}
		if (thisFour >= 4)
		{
			alert('You can only select 4 packages total.<br/><br/><u>You have selected the following</u>:<br/>' + thisSelectedProduct);
		}
		else
		{
		thisHidden.value = thisProduct;
		thisIMG.style.border = '10px solid blue';
		}
	}
	else
	{
		thisHidden.value = '';
		thisIMG.style.border = '10px solid transparent';
	}
}

function checkSamplerSelection() {
	var thisFour = 0;
	var thisProduct;
	var thisSelectedProduct = '';

	for (var i = 0; i < document.getElementById('samplerForm').elements.length; i++ ) {
		if ((document.getElementById('samplerForm').elements[i].type == 'hidden') && (document.getElementById('samplerForm').elements[i].name != 'YourChoiceSubmitted')) {
			if (document.getElementById('samplerForm').elements[i].value != '') {
				thisFour = thisFour + 1;
				if (thisFour == 1)
				{
					thisSelectedProduct = document.getElementById('samplerForm').elements[i].value;
				}
				else
				{
					thisSelectedProduct = thisSelectedProduct + ', ' + document.getElementById('samplerForm').elements[i].value;
				}
			}
		}
	}
	if (thisFour < 4)
	{
		alert('Please select 4 packages.');
		return false;
	}
	else
	{
		if (document.samplerForm.ProductID[0].checked)
		{
			thisSelectedProduct = '(7 oz.) ' + thisSelectedProduct;
		}
		else
		{
			thisSelectedProduct = '(1.5 oz.) ' + thisSelectedProduct;
		}
		document.getElementById('PackageSelected').value = thisSelectedProduct;
		return true;
	}
}

function divShowHideCheckout(thisID)
{
	document.getElementById('divLogin').style.display='none';
	document.getElementById('divCreate').style.display='none';
	document.getElementById('divSkip').style.display='none';
	if (thisID == 'login')
		document.getElementById('divLogin').style.display='block';
	if (thisID == 'create')
		document.getElementById('divCreate').style.display='block';
	if (thisID == 'skip')
		document.getElementById('divSkip').style.display='block';
}

function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setMapType(G_HYBRID_MAP);
    { size: new GSize(500,300) } ;
	  map.setCenter(new GLatLng(41.881621, -87.625675), 17);
	  toAddress = "19 S. Wabash Ave. Chicago, IL 60603"; 
	  var marker = new GMarker(new GLatLng(41.881621, -87.625675))
	  gdir  = new GDirections(map, document.getElementById("directions"));
	  GEvent.addListener(marker, 'click', function() {
	  marker.openInfoWindowHtml('<div><img src="https://www.iwanries.com/images/IRC_Logo_sm.gif" align="left">Iwan Ries &amp; Co.<br />19 S. Wabash Ave.<br />Chicago, IL 60603<br />1-800-621-1457</div>'); 
    }); 
	  map.addOverlay(marker);
	  map.setUIToDefault();
      }
    }
function overlayDirections()
{
    fromAddress =
      document.getElementById("street").value
      + " " + document.getElementById("city").value
      + " " + document.getElementById("state").options[document.getElementById("state").selectedIndex].value
      + " " + document.getElementById("zip").value;
    
    var language  = document.getElementById("language").options[document.getElementById("language").selectedIndex].value;
    
    gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": language });
	return false;
}
function createMarker(latlng, imageURL, imageSize)
{
  
    var marker      = new GIcon(G_DEFAULT_ICON);
    marker.image    = imageURL;
    marker.iconSize = imageSize;
    
    var options     =  { icon: marker };
    
    return new GMarker(latlng, options);
  
}
function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
   else alert("An unknown error occurred.");
}

    __AutoComplete = new Array();

    isIE = document.all ? true : false;
    isGecko = navigator.userAgent.toLowerCase().indexOf('gecko') != -1;
    isOpera = navigator.userAgent.toLowerCase().indexOf('opera') != -1;

function AutoComplete_Create (id, data)
    {
        __AutoComplete[id] = {'data':data,
                              'isVisible':false,
                              'element':document.getElementById(id),
                              'dropdown':null,
                              'highlighted':null};

        __AutoComplete[id]['element'].setAttribute('autocomplete', 'off');
        __AutoComplete[id]['element'].onkeydown  = function(e) {return AutoComplete_KeyDown(this.getAttribute('id'), e);}
        __AutoComplete[id]['element'].onkeyup    = function(e) {return AutoComplete_KeyUp(this.getAttribute('id'), e);}
        __AutoComplete[id]['element'].onkeypress = function(e) {if (!e) e = window.event; if (e.keyCode == 13 || isOpera) return false;}
        __AutoComplete[id]['element'].ondblclick = function() {AutoComplete_ShowDropdown(this.getAttribute('id'));}
        __AutoComplete[id]['element'].onclick    = function(e) {if (!e) e = window.event; e.cancelBubble = true; e.returnValue = false;}

        var docClick = function()
        {
           for (id in __AutoComplete) {
               AutoComplete_HideDropdown(id);
           }
        }

        if (document.addEventListener) {
            document.addEventListener('click', docClick, false);
        } else if (document.attachEvent) {
            document.attachEvent('onclick', docClick, false);
        }


        if (arguments[2] != null) {
            __AutoComplete[id]['maxitems'] = arguments[2];
            __AutoComplete[id]['firstItemShowing'] = 0;
            __AutoComplete[id]['lastItemShowing']  = arguments[2] - 1;
        }
        
        AutoComplete_CreateDropdown(id);
        
        if (isIE) {
            __AutoComplete[id]['iframe'] = document.createElement('iframe');
            __AutoComplete[id]['iframe'].id = id +'_iframe';
            __AutoComplete[id]['iframe'].style.position = 'absolute';
            __AutoComplete[id]['iframe'].style.top = '0';
            __AutoComplete[id]['iframe'].style.left = '0';
            __AutoComplete[id]['iframe'].style.width = '0px';
            __AutoComplete[id]['iframe'].style.height = '0px';
            __AutoComplete[id]['iframe'].style.zIndex = '98';
            __AutoComplete[id]['iframe'].style.visibility = 'hidden';
            
            __AutoComplete[id]['element'].parentNode.insertBefore(__AutoComplete[id]['iframe'], __AutoComplete[id]['element']);
        }
    }


    function AutoComplete_CreateDropdown(id)
    {
        var left  = AutoComplete_GetLeft(__AutoComplete[id]['element']);
        var top   = AutoComplete_GetTop(__AutoComplete[id]['element']) + __AutoComplete[id]['element'].offsetHeight;
        var width = __AutoComplete[id]['element'].offsetWidth;
    
        __AutoComplete[id]['dropdown'] = document.createElement('div');
        __AutoComplete[id]['dropdown'].className = 'autocomplete';
    
        __AutoComplete[id]['element'].parentNode.insertBefore(__AutoComplete[id]['dropdown'], __AutoComplete[id]['element']);
        
        __AutoComplete[id]['dropdown'].style.left       = left + 'px';
        __AutoComplete[id]['dropdown'].style.top        = top + 'px';
        __AutoComplete[id]['dropdown'].style.width      = width + 'px';
        __AutoComplete[id]['dropdown'].style.zIndex     = '99';
        __AutoComplete[id]['dropdown'].style.visibility = 'hidden';
    }
    
    
    function AutoComplete_GetLeft(element)
    {
        var curNode = element;
        var left    = 0;

        do {
            left += curNode.offsetLeft;
            curNode = curNode.offsetParent;

        } while(curNode.tagName.toLowerCase() != 'body');

        return left;
    }
    
    
    function AutoComplete_GetTop(element)
    {
        var curNode = element;
        var top    = 0;

        do {
            top += curNode.offsetTop;
            curNode = curNode.offsetParent;

        } while(curNode.tagName.toLowerCase() != 'body');

        return top;
    }

    function AutoComplete_ShowDropdown(id)
    {
        AutoComplete_HideAll();

        var value = __AutoComplete[id]['element'].value;
        var toDisplay = new Array();
        var newDiv    = null;
        var text      = null;
        var numItems  = __AutoComplete[id]['dropdown'].childNodes.length;

        while (__AutoComplete[id]['dropdown'].childNodes.length > 0) {
            __AutoComplete[id]['dropdown'].removeChild(__AutoComplete[id]['dropdown'].childNodes[0]);
        }

        for (i=0; i<__AutoComplete[id]['data'].length; ++i) {
            if (__AutoComplete[id]['data'][i].substr(0, value.length).toLowerCase() == value.toLowerCase()) {
                toDisplay[toDisplay.length] = __AutoComplete[id]['data'][i];
            }
        }
        
        if (toDisplay.length == 0) {
            AutoComplete_HideDropdown(id);
            return;
        }



        for (i=0; i<toDisplay.length; ++i) {
            newDiv = document.createElement('div');
            newDiv.className = 'autocomplete_item';
            newDiv.setAttribute('id', 'autocomplete_item_' + i);
            newDiv.setAttribute('index', i);
            newDiv.style.zIndex = '99';
            
            if (toDisplay.length > __AutoComplete[id]['maxitems'] && navigator.userAgent.indexOf('MSIE') == -1) {
                newDiv.style.width = __AutoComplete[id]['element'].offsetWidth - 22 + 'px';
            }

            newDiv.onmouseover = function() {AutoComplete_HighlightItem(__AutoComplete[id]['element'].getAttribute('id'), this.getAttribute('index'));};
            newDiv.onclick     = function() {AutoComplete_SetValue(__AutoComplete[id]['element'].getAttribute('id')); AutoComplete_HideDropdown(__AutoComplete[id]['element'].getAttribute('id'));}
            
            text   = document.createTextNode(toDisplay[i]);
            newDiv.appendChild(text);
            
            __AutoComplete[id]['dropdown'].appendChild(newDiv);
        }
        
        
        if (toDisplay.length > __AutoComplete[id]['maxitems']) {
            __AutoComplete[id]['dropdown'].style.height = (__AutoComplete[id]['maxitems'] * 15) + 2 + 'px';
        
        } else {
            __AutoComplete[id]['dropdown'].style.height = '';
        }

        
        __AutoComplete[id]['dropdown'].style.left = AutoComplete_GetLeft(__AutoComplete[id]['element']);
        __AutoComplete[id]['dropdown'].style.top  = AutoComplete_GetTop(__AutoComplete[id]['element']) + __AutoComplete[id]['element'].offsetHeight;


        if (isIE) {
            __AutoComplete[id]['iframe'].style.top    = __AutoComplete[id]['dropdown'].style.top;
            __AutoComplete[id]['iframe'].style.left   = __AutoComplete[id]['dropdown'].style.left;
            __AutoComplete[id]['iframe'].style.width  = __AutoComplete[id]['dropdown'].offsetWidth;
            __AutoComplete[id]['iframe'].style.height = __AutoComplete[id]['dropdown'].offsetHeight;
            
            __AutoComplete[id]['iframe'].style.visibility = 'visible';
        }


        if (!__AutoComplete[id]['isVisible']) {
            __AutoComplete[id]['dropdown'].style.visibility = 'visible';
            __AutoComplete[id]['isVisible'] = true;
        }

        
        if (__AutoComplete[id]['dropdown'].childNodes.length != numItems) {
            __AutoComplete[id]['highlighted'] = null;
        }
    }
    
    function AutoComplete_HideDropdown(id)
    {
        if (__AutoComplete[id]['iframe']) {
            __AutoComplete[id]['iframe'].style.visibility = 'hidden';
        }


        __AutoComplete[id]['dropdown'].style.visibility = 'hidden';
        __AutoComplete[id]['highlighted'] = null;
        __AutoComplete[id]['isVisible']   = false;
    }
    
    
    function AutoComplete_HideAll()
    {
        for (id in __AutoComplete) {
            AutoComplete_HideDropdown(id);
        }
    }
    
    
    function AutoComplete_HighlightItem(id, index)
    {
        if (__AutoComplete[id]['dropdown'].childNodes[index]) {
            for (var i=0; i<__AutoComplete[id]['dropdown'].childNodes.length; ++i) {
                if (__AutoComplete[id]['dropdown'].childNodes[i].className == 'autocomplete_item_highlighted') {
                    __AutoComplete[id]['dropdown'].childNodes[i].className = 'autocomplete_item';
                }
            }
            
            __AutoComplete[id]['dropdown'].childNodes[index].className = 'autocomplete_item_highlighted';
            __AutoComplete[id]['highlighted'] = index;
        }
    }


    function AutoComplete_Highlight(id, index)
    {
        if (index == 1 && __AutoComplete[id]['highlighted'] == __AutoComplete[id]['dropdown'].childNodes.length - 1) {
            __AutoComplete[id]['dropdown'].childNodes[__AutoComplete[id]['highlighted']].className = 'autocomplete_item';
            __AutoComplete[id]['highlighted'] = null;
        
        } else if (index == -1 && __AutoComplete[id]['highlighted'] == 0) {
            __AutoComplete[id]['dropdown'].childNodes[0].className = 'autocomplete_item';
            __AutoComplete[id]['highlighted'] = __AutoComplete[id]['dropdown'].childNodes.length;
        }

        if (__AutoComplete[id]['highlighted'] == null) {
            __AutoComplete[id]['dropdown'].childNodes[0].className = 'autocomplete_item_highlighted';
            __AutoComplete[id]['highlighted'] = 0;

        } else {
            if (__AutoComplete[id]['dropdown'].childNodes[__AutoComplete[id]['highlighted']]) {
                __AutoComplete[id]['dropdown'].childNodes[__AutoComplete[id]['highlighted']].className = 'autocomplete_item';
            }

            var newIndex = __AutoComplete[id]['highlighted'] + index;

            if (__AutoComplete[id]['dropdown'].childNodes[newIndex]) {
                __AutoComplete[id]['dropdown'].childNodes[newIndex].className = 'autocomplete_item_highlighted';
                
                __AutoComplete[id]['highlighted'] = newIndex;
            }
        }
    }


    function AutoComplete_SetValue(id)
    {
        __AutoComplete[id]['element'].value = __AutoComplete[id]['dropdown'].childNodes[__AutoComplete[id]['highlighted']].innerHTML;
		__AutoComplete[id]['element'].focus();
    }
    
    
    function AutoComplete_ScrollCheck(id)
    {
        if (__AutoComplete[id]['highlighted'] > __AutoComplete[id]['lastItemShowing']) {
            __AutoComplete[id]['firstItemShowing'] = __AutoComplete[id]['highlighted'] - (__AutoComplete[id]['maxitems'] - 1);
            __AutoComplete[id]['lastItemShowing']  = __AutoComplete[id]['highlighted'];
        }
        
        if (__AutoComplete[id]['highlighted'] < __AutoComplete[id]['firstItemShowing']) {
            __AutoComplete[id]['firstItemShowing'] = __AutoComplete[id]['highlighted'];
            __AutoComplete[id]['lastItemShowing']  = __AutoComplete[id]['highlighted'] + (__AutoComplete[id]['maxitems'] - 1);
        }
        
        __AutoComplete[id]['dropdown'].scrollTop = __AutoComplete[id]['firstItemShowing'] * 15;
    }


    function AutoComplete_KeyDown(id)
    {
        if (arguments[1] != null) {
            event = arguments[1];
        }

        var keyCode = event.keyCode;

        switch (keyCode) {

            case 13:
                if (__AutoComplete[id]['highlighted'] != null) {
                    AutoComplete_SetValue(id);
                    AutoComplete_HideDropdown(id);
                }
                
                event.returnValue = false;
                event.cancelBubble = true;
                break;

            case 27:
                AutoComplete_HideDropdown(id);
                event.returnValue = false;
                event.cancelBubble = true;
                break;
            
            case 38:
                if (!__AutoComplete[id]['isVisible']) {
                    AutoComplete_ShowDropdown(id);
                }
                
                AutoComplete_Highlight(id, -1);
                AutoComplete_ScrollCheck(id, -1);
                return false;
                break;
            
            case 9:
                if (__AutoComplete[id]['isVisible']) {
                    AutoComplete_HideDropdown(id);
                }
                return;
            
            case 40:
                if (!__AutoComplete[id]['isVisible']) {
                    AutoComplete_ShowDropdown(id);
                }
                
                AutoComplete_Highlight(id, 1);
                AutoComplete_ScrollCheck(id, 1);
                return false;
                break;
        }
    }

    function AutoComplete_KeyUp(id)
    {
        if (arguments[1] != null) {
            event = arguments[1];
        }

        var keyCode = event.keyCode;

        switch (keyCode) {
            case 13:
                event.returnValue = false;
                event.cancelBubble = true;
                break;

            case 27:
                AutoComplete_HideDropdown(id);
                event.returnValue = false;
                event.cancelBubble = true;
                break;
            
            case 38:
            case 40:
                return false;
                break;

            default:
                AutoComplete_ShowDropdown(id);
                break;
        }
    }
    
    function AutoComplete_isVisible(id)
    {
        return __AutoComplete[id]['dropdown'].style.visibility == 'visible';
    }
	
var ALERT_TITLE = "Iwan Ries & Co.";
var ALERT_BUTTON_TEXT = "Ok";
 
if(document.getElementById) {
  window.alert = function(txt) {
    createCustomAlert(txt);
  }
}
 
function createCustomAlert(txt) {
  d = document;
 
  if(d.getElementById("modalContainer")) return;
 
  mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
  mObj.id = "modalContainer";
  mObj.style.height = document.documentElement.scrollHeight + "px";
 
  alertObj = mObj.appendChild(d.createElement("div"));
  alertObj.id = "alertBox";
  h1 = alertObj.appendChild(d.createElement("h1"));
  h1.appendChild(d.createTextNode(ALERT_TITLE));
  msg = alertObj.appendChild(d.createElement("p"));
  msg.innerHTML = txt;
  btn = alertObj.appendChild(d.createElement("a"));
  btn.id = "closeBtn";
  btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
  btn.href = "#";
  btn.onclick = function() { removeCustomAlert();return false; }
}
 
function removeCustomAlert() {
  document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}


function AC_AX_RunContent(){
  var ret = AC_AX_GetArgs(arguments);
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_AX_GetArgs(args){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "pluginspage":
      case "type":
      case "src":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "data":
      case "codebase":
      case "classid":
      case "id":
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  return ret;
}
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

theObjects = document.getElementsByTagName("object"); 
for (var i = 0; i < theObjects.length; i++) { 
theObjects[i].outerHTML = theObjects[i].outerHTML; 
} 
