var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) 
{
    var keyCode = (isNN) ? e.which : e.keyCode; 
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode)) 
    {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
	}
	function containsElement(arr, ele) {
	    var found = false, index = 0;
	    while(!found && index < arr.length)
	    if(arr[index] == ele)
	    	found = true;
	    else
		    index++;
	    return found;
	}
	function getIndex(input) {
	    var index = -1, i = 0, found = false;
	    while (i < input.form.length && index == -1)
	        if (input.form[i] == input)index = i;
	        else i++;
	    return index;
	}
	return true;
}
function updateList(listId, json) {
    for (var key in json.courses ) {
        addOption(listId, json.courses[key].title, json.courses[key].program_code, json.courses[key].program_style);
    }
}

function updateProgramList(request, json) {
    var listId = $('course');
    listId.length = 0;
    
    addOption(listId, ' -- Select a Program -- ', '', 'core');
    //addOption(listId, 'Not Sure', 'NS');
    updateList(listId, json);
    if(json.city != '' && json.city != null)
    {
    	updateCity(json.city);
    }
    if(json.state != '' && json.state != null)
    {
    	updateState(json.state);
    }
    $('course-loading').style.display = 'none';
}

function updateCity(city)
{
	if(city != null && city != "")
	{
		$('city').value = city;
	}
}

function updateState(state)
{
	if(state != null && state != "")
	{
		for(var i=0; i<$('state').length;i++)
		{
			if($('state').options[i].value == state)
			{
				$('state').selectedIndex = i;
			}
		}
	}
}

function showLoading(el)
{
	el.style.display = 'inline';
}
var last_core = '';
function addOption(list, text, value, style) {
    option = document.createElement('option');
    if(style != 'core')
   	{
   		text = ' -- ' + text;
   		option.title = last_core;
   	}
   	else
   	{
   		last_core = text;
   	}
    option.text = text;
    option.className = style;
    if ( value != "undefined" ) {
        option.value = value;
    }

    try {
        list.add(option, null); // Standards compliant
    }
    catch (ex) {
        list.add(option); // IE isn't compliant
    }
}
Event.observe(window, 'load', function()
{
	new Form.Element.EventObserver("zipcode", function(element, value)
	{
		new Ajax.Request('/contact/core_search', {asynchronous:true, evalScripts:false, onCreate:function(request, json)
		{
			showLoading($('course-loading'));
		}, onComplete:function(request, json)
		{
			updateProgramList(request, json)
		}, parameters:'zipcode=' + $F('zipcode'), method: 'GET'})
	});
});
