
// the number of entries to display in the dropdown, leave as 0 for all entries
var max_matched_entries = 0;    

// the number of entries to display in the dropdown when no text has been typed. (the 'Type a name' counts as one, so to just display that, use 1)
var max_default_entries = 1;

// some key codes
var VK_TAB          = 9;
var VK_ENTER        = 13;
var VK_UP           = 38;
var VK_DOWN         = 40;


function observeEvent(element, eventname, f)
{
    function tie_event(event)
    {
        return f(event ? event : window.event);
    }
    if (element.addEventListener)
    {
        element.addEventListener(eventname, tie_event, false);
    }
    else if (element.attachEvent)
    {
        element.attachEvent("on" + eventname, tie_event);
    }    
}

function trim(s)
{
    return s.replace(/^[ \t]+|[ \t]+$/, "");
}

function cancelEvent(event)
{
	if (!event) { event = window.event; }
	event.returnValue = false;
	if (event.preventDefault)
	{
		event.preventDefault();
	}
	return false;
}

function stopPropagation(event)
{
    if (!event) { event = window.event; }
    event.cancelBubble = true
    if (event.stopPropagation)
    {
        event.stopPropagation();
    }
}

function getElementPosition(element)
{
    var x = 0;
    var y = 0;
    var node = element;
    while(node && node.nodeName != "BODY" && node.nodeName != "body")
    {
        x += node.offsetLeft;
        y += node.offsetTop;
        node = node.offsetParent;
    }
    return {left : x, top : y, right : x + element.offsetWidth, bottom : y + element.offsetHeight}; 
}

function findIndexOfChildNode(parent, child)
{
    for(var n in parent.childNodes)
    {
        if (child == parent.childNodes[n])
        {
            return n;
        }
    }
    return -1;
}


function setCursorRange(textbox, start, end)
{
    if( textbox.setSelectionRange ) 
    {
        textbox.setSelectionRange(start,end);
    } 
    else if( textbox.createTextRange ) 
    {
        var range = textbox.createTextRange();
        range.collapse(true);
        range.moveEnd('character',end);
        range.moveStart('character',start);
        range.select();
    }
    textbox.focus();
}

function setCursorPosition(textbox, pos)
{
    setCursorRange(textbox, pos, pos);
}

function setCursorEnd(textbox)
{
    setCursorPosition(textbox, textbox.value.length);
}

function regex_clean_text(text)
{
    return text.replace(/([\.\\\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}


function Suggestion(plain_text, html)
{
    this.plain_text =   plain_text;
    this.html       =   html;
}

function GolferNamesSuggester(text)
{
    var matches = new Array();
    if (text === '')
    {
        matches.push(new Suggestion('', "<i>Type a name</i>"));
        var max = max_default_entries == 0 ? names.length : max_default_entries;
        for (var n = 0; n < max - 1; ++n)
        {
            matches.push(new Suggestion(names[n],names[n]));
        }
    }
    else
    {
        text = regex_clean_text(text);
        var already_added = new Array();
        var res = new Array(new RegExp('^(' + text + ")", "i"), 
                            new RegExp('\\b(' + text + ")", "i"),
                            new RegExp("(" + text + ")", "i"));
        var max = max_matched_entries == 0 ? names.length : max_matched_entries;
        for (var re in res)
        {
            for (var name in names)
            {
                if (matches.length >= max)
                {
                    return matches;
                }
                if (!already_added[name] && res[re].test(names[name]))
                {
                    already_added[name] = true;
                    var replace_re = re == 2 ? new RegExp("(" + text + ")", "ig") : new RegExp("\\b(" + text + ")", "ig");
                    matches.push(new Suggestion(names[name], names[name].replace(replace_re, "<b>$1</b>")));
                }
            }
        }
    }
    return matches;
}

function enableAutoSuggest(textbox, suggester, enable_match_highlighting)
{
    var selected_match      =   0;

    var dropdown            =   document.createElement('ul');
    var current_text        =   -1;
    var cancel_bubble       =   false;      // not using real cancelBubble because we only want to cancel it for this object
    dropdown.className      =   'dropdown_list';
    document.body.appendChild(dropdown);

    function onHide() 
    {
        if (!cancel_bubble)
        {
            dropdown.style.display = 'none';
        }
        cancel_bubble = false;
    }
    observeEvent(document, "click", onHide);
    
    function cancelInternalBubble()
    {   // the user clicked the input, or used the scroll bar, stop the event from bubbling up to the document onclick handler.
        cancel_bubble = true;
    }
    observeEvent(textbox, "click", cancelInternalBubble);
    
    function select_current_suggestion()
    {
        if (selected_match >= 0 && selected_match < dropdown.childNodes.length)
        {
            if (dropdown.childNodes[selected_match].className != 'error')
            {
                textbox.value = dropdown.childNodes[selected_match].title;
            }
            setCursorEnd(textbox);
            selected_match = 0;
            dropdown.style.display = 'none';
        }
    }
    
    function set_selected_match(new_selected_match)
    {
        if (new_selected_match >= 0 && new_selected_match < dropdown.childNodes.length)
        {
            if (selected_match >= 0 && selected_match < dropdown.childNodes.length && dropdown.childNodes[selected_match].className != 'error') 
            {
                dropdown.childNodes[selected_match].className = '';
            }
            selected_match = new_selected_match;
            if (dropdown.childNodes[selected_match].title !== '' && dropdown.childNodes[selected_match].className != 'error')
            {
                dropdown.childNodes[selected_match].className = 'selected';
            }
        }
    }
    
    function onClickSuggestion(event)
    {
        select_current_suggestion();
        stopPropagation();
        cancelInternalBubble();
        textbox.focus();
    }
    
    function onMouseOverSuggestion(event)
    { 	
        var node = event.srcElement ? event.srcElement : event.target;
        while (node && node.tagName != 'LI' && node.tagName != 'li')
        {
            node = node.parentNode;
        }
        if (node && node.className != 'error')
        {
            set_selected_match(findIndexOfChildNode(dropdown, node));
        }
    };
        
    // not sure why I need to do add and attach, but onmouseover= doesn't seem to bubble in IE??
    observeEvent(dropdown, "mouseover", onMouseOverSuggestion);
    observeEvent(dropdown, "click", onClickSuggestion);
    
    textbox.onkeydown = function( event)
    {   // handle any key presses that we might want to cancel
        if (!event) { event = window.event; }
        switch (event.keyCode ? event.keyCode : event.charCode)
        {
            case VK_ENTER :
		        cancelInternalBubble();
                select_current_suggestion();
                return cancelEvent(event);
            
            case VK_TAB : 
                select_current_suggestion();
                break;
                
            case VK_UP : 
                set_selected_match(selected_match - 1);
                break;
                
            case VK_DOWN :
                set_selected_match(selected_match + 1);
                break;
        }
        return true;
    };
    
    // opera likes us to cancel the event in onkeypress : 
    textbox.onkeypress  = 	function(event)
    {
        if (!event) { event = window.event; }
        switch (event.keyCode ? event.keyCode : event.charCode)
        {
            case VK_ENTER :
                return cancelEvent(event);
            default: 
            	return true;
        }    
    }
       
    textbox.onkeyup     =   update_dropdown;    
    textbox.onfocus     =   update_dropdown;
    
    // whenever we need to display/update the dropdown in response to a user event of some sort.    
    function update_dropdown()
    {    
    	if (cancel_bubble)
    	{	// if the user pressed enter, we don't want to redisplay the dropdown.
    		cancel_bubble = false;
    		return;
    	}
        var position = getElementPosition(textbox);
        dropdown.style.left = position.left + "px";
        dropdown.style.top = position.bottom + "px";
        dropdown.style.display = 'block';
        
        
        if (current_text != trim(textbox.value))
        {
            current_text = trim(textbox.value);

	        if (current_text == '')
	        {
		        dropdown.className += " default_dropdown_list";
	        }
	        else
	        {
		        dropdown.className = dropdown.className.replace(/ ?default_dropdown_list/, "");
	        }
            
            var matches  = suggester(current_text);
            var strings = Array();
            for (var match in matches)
            {
                strings[strings.length] = "<li title=\"" + matches[match].plain_text + "\">" + matches[match].html + "</li>";
            }
            if (!matches.length)
            {
                strings[strings.length] = "<li class=\"error\" title=\"Sorry, no names found that matched your search string\">No names matched</li>";
            }
            // (no need to purge all the children here, 1) it takes too long, 2) we have no children with event handlers, so no circular references are created)
            dropdown.innerHTML = strings.join('');
            set_selected_match(0);
        }
    }
}

function initEmailObjects()
{
	if (document.form_guide_homepage)
	{
		if (document.form_guide_homepage.golferentry1)
		{
    		enableAutoSuggest(document.form_guide_homepage.golferentry1,  GolferNamesSuggester);
    	}
    	if (document.form_guide_homepage.golferentry2)
    	{
    		enableAutoSuggest(document.form_guide_homepage.golferentry2,  GolferNamesSuggester);
    	}
    }
}
observeEvent(window, "load", initEmailObjects);


function check1()
{
	if((document.form_guide_homepage.golferentry1.value=="") || (document.form_guide_homepage.golferentry1.value=="GOLFER 1"))
	{
		alert("The GOLFER 1 field is mandatory. You must enter a golfers name!");
		document.form_guide_homepage.golferentry1.focus();
		return false;
	}
	return true;
}