function indexEffect(image, show) {
	if(show) {
		$('#snapshot').css('backgroundImage', 'url('+image+')').animate({opacity: 1}, 'slow');
	}
	else {
		$('#snapshot').animate({opacity: 0}, 'slow'); 
		window.setTimeout('indexEffect(\''+image+'\', true)', 700);
	}
}

function ratingHover(start, page, id, disabled) {
	for(var i = 1; i <= start; i++) {
		$('.rating img.' + i).attr('src', '/_images/star.gif');
	}
	
	if(!disabled) {
	
		// add to all a elements a hover			
		$('.rating img').hover(function() {
			var current = parseInt($(this).attr('class'), 10); 
			current--;
			
			for(var i = 1; i <= current; i++) {
				$('.rating img.' + i).attr('src', '/_images/star.gif');
			}
			
			$(this).attr('src', '/_images/star.gif');
		}, 
		function() {
			
			for(var i = 5; i >= 1; i--) {
				$('.rating img.' + i).attr('src', '/_images/star_empty.gif');
			}
			
		});
		
	}
	
	if(!disabled) {
	
		// bind click event to all
		$('.rating img').click(function() {
			// send rating via ajax to server
			try {
				var rating = $(this).attr('class'); 
				
				jQuery.ajax({type: "POST", url: "/"+ page +"/,rating,"+id+",,,"+rating+"",
					success: function(data) {
						var html = $('.rating').html();
						$('.rating').html('<span class="green size11">Danke f&uuml;r deine Stimme</span>');
						$('#rates').html(parseInt($('#rates').html(), 10) + 1);
						
						$('.rating').html(html);
						ratingHover(data, page, id, true);
					}});
				
				return false;
			}
			catch(e) {}
	});
	
	}
}

function ratingHoverArena(start, type, id, disabled) {
	//alert(disabled);
	for(var i = 1; i <= start; i++) {
		$('.rating_'+type+' img.' + i).attr('src', '/_images/star.gif');
	}
	
	if(!disabled) {
	
		// add to all a elements a hover
		$('.rating_'+type+' img').hover(function() {
			var current = parseInt($(this).attr('class'), 10); 
			current--;
			
			for(var i = 1; i <= current; i++) {
				$('.rating_'+type+' img.' + i).attr('src', '/_images/star.gif');
			}
			
			$(this).attr('src', '/_images/star.gif');
		}, 
		function() {
			
			for(var i = 5; i >= 1; i--) {
				$('.rating_'+type+' img.' + i).attr('src', '/_images/star_empty.gif');
			}
			
		});
		
	}
	
	if(!disabled) {
	
		// bind click event to all
		$('.rating_'+type+' img').click(function() {
			// send rating via ajax to server
			//try {
				var rating = $(this).attr('class'); 
				
				jQuery.ajax({type: "POST", url: "/"+ 'dasstadion' +"/,"+type+","+id+",,,"+rating+"",
					success: function(data) {		
						$('.rating_'+type+' img').unbind();			
						for(var i = 1; i <= rating; i++) {
							$('.rating_'+type+' img.' + i).attr('src', '/_images/star.gif');
						}
						
						//ratingHoverArena(data, type, id, true);
					}});
					
					
				
				return false;
			//}
			//catch(e) {}
	});
	
	}
}

function imageOfTheDay(id) {
	jQuery.ajax({type: "POST", url: "/bild-des-tages/,,"+id+",,,,",
	success: function(data) {
	}});
}

function nominateImageOfTheMonth(e, id, user) {

	if (user == 1) {
		// User is authenticated
		jQuery.ajax({type: "POST", url: "/vorschlag-foto-des-monats/,,"+id+",1,,,",		// 1 = ajax, so no redirection afterwards
			success: function(data) {
				$(e).remove();
				$('#nominate_success').show();
			}
		});
	} else {
		// User is not authenticated
		window.location.href = '/vorschlag-foto-des-monats/,,'+id+',,,,';				// nothing, so no ajax, so redirect the user after login
																						// and action back to this page
	}
	return false;
}

function makeTopnews(id) {
	jQuery.ajax({type: "GET", url: "/topnews/,,"+id+",,,,",
	success: function(data) {
		alert('Fertig!');
	}});
}

function isSnapshot(id,name) {
	jQuery.ajax({type: "POST", url: "/snapshot/,"+name+","+id+",,,,",
	success: function(data) {
	}});
}

function removeSnapshot(id) {
	jQuery.ajax({type: "POST", url: "/remove-snapshot/,,"+id+",,,,",
	success: function(data) {
	}});
}

function deleteClubFan(club_id, element) {
	$(element).hide('slow');
	
	jQuery.ajax({type: "POST", url: "/verein-entfanen/,,"+club_id+",,,,",
	success: function(data) {
	}});
	
}

function deleteFan(owner, user, element) {
	$(element).hide('slow');
	
	jQuery.ajax({type: "POST", url: "/entfanen/,"+page+","+owner+",,,,", data: "user_id="+user,
	success: function(data) {
		count = parseInt($('.fan_count').html(), 10);
		if (count > 1) {
			$('.fan_count').html(count - 1);
		} else {
			$('.fan_count').html('0');
		}
		
	}});
	
}

function deleteGroupMember(group, user, element) {
	$(element).hide('slow');
	var count = parseInt($('#member_count').html(), 10)-1;
	
	jQuery.ajax({type: "POST", url: "/gruppen-mitglied-entfernen/,"+group+","+user+",,,,",
	success: function(data) {
		// data is html of comments
	}});
	
	if(count == 0) {
		$('.noentry').show();
	}
	
	$('#member_count').html(count);
}

function getComments(page, id) {
	$('#comments').animate({'opacity': 'hide'}, 'slow');
	
	jQuery.ajax({type: "GET", url: "/kommentare/,"+page+","+id+",,,,",
	success: function(data) {
		// data is html of comments
		$('#comments').html(data).animate({'opacity': 'show'}, 'slow');
	}});
}

function addComment(page, id) {
	var text = $('#comment textarea[@name=text]').val();
	
	if(text.length >= 3) {
		
		jQuery.ajax({type: "POST", url: "/kommentar-hinzufuegen/,"+page+","+id+",,,,", data: 'text='+text,
		success: function(data) {
			$('#comments').animate({'opacity': 'hide'}, 'slow');
			$('#comments').html(data).animate({'opacity': 'show'}, 'slow');
			$('#comment textarea[@name=text]').val('');
		}});
	
	}
}

function deleteComment(id) {
	jQuery.ajax({type: "POST", url: "/kommentar-loeschen/,,"+id+",,,,",
	success: function(data) {
		$('#comment_' + id).remove();
	}});
}

function deleteGuestbook(id, page, optional) {
	jQuery.ajax({type: "POST", url: "/gaestebuch-loeschen/,"+page+","+id+",,,"+optional,
	success: function(data) {
		$('#guestbook_' + id).remove();
		var crnt = parseInt($('.guestbook_count').html(), 10);
		$('.guestbook_count').html("" + crnt - 1 + "");
	}});
}

function deleteUserEvent(id) {
	jQuery.ajax({type: "GET", url: "/remove-event/,,"+id+",,,,",
	success: function(data) {
		$('#event_' + id).remove();
	}});
}

var doTicker = true;

$(document).ready(function () {
	$('ul.menu li a').click(function () {
		doTicker = false;
	});
	
	$('#ticker').unload(function () {
		doTicker = false;
	});
});

function getTicker() {
	$('#ticker').animate({'opacity': 'hide'}, 'slow');
	var i = Math.round(10000*Math.random());
	jQuery.ajax({type: 'GET', url: 'ticker/,,,,,,/?a='+i,
	success: function(data) {
		if(data != "" && $('#ticker').html() != data) {
			// data is html of guestbook
			$('#ticker').html(data).animate({'opacity': 'show'}, 'slow');
		}
	}});
	
	if(doTicker)
		window.setTimeout('getTicker()', 7500);
	
}

function getGuestbook(page, id) {
	$('#guestbook').animate({'opacity': 'hide'}, 'slow');
	
	jQuery.ajax({type: "GET", url: "/gaestebuch/,"+page+","+id+",,,,",
	success: function(data) {
		// data is html of guestbook
		$('#guestbook').html(data).animate({'opacity': 'show'}, 'slow');
	}});
}

function addGuestbook(page, id) {
	var text = $('#text').val();
	
	if(text != null && text.length >= 3) {
		$('.error').remove();
	
		jQuery.ajax({type: "POST", url: "/gaestebuch/,"+page+","+id+",,,,", data: 'text='+text,
		success: function(data) {
			var crnt = parseInt($('.guestbook_count').html(), 10);
			$('.guestbook_count').html(crnt + 1);
				
			getGuestbook(page, id);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$('#error').show('slow');
		}
			
		});
	
	}
	
	$('#text').val('');
	$('.error').remove();
}

function fireUserEvent(type, user_id) {
	jQuery.ajax({type: "POST", url: "/profil-aktion/,,,,,,", data: "user_id="+user_id+"&type="+type,
		success: function(data) {
			
		}});
}

function addClubFan(club_id) {
	if(club_id == false) {
		$('.fan').attr('src', '/_images/fan_success.png');
		$('.fan').parent().attr('href', '/startseite/vereine/fans/,,'+club_id+',,,,');
		$('.fan').parent().css('top', '-125px');
		$('.fan').animate({opacity:1}, 'slow');
	}
	else {
		jQuery.ajax({type: "POST", url: "/fan-werden/,club,"+club_id+",,,,",
		success: function(data) {
			$('.fan').animate({opacity:0}, 'slow');
			setTimeout('addClubFan(false)', 200);
			$('.fan_count').html(parseInt($('.fan_count').html(), 10) + 1);
		}});
	}
}

function addUserFan(user_id) {
	if(user_id == false) {
		$('.fan').attr('src', '/_images/fan_success.png');
		$('.fan').parent().attr('href', '/startseite/vereine/benutzer-fans/,,'+user_id+',,,,');
		$('.fan').parent().css('top', '-125px');
		$('.fan').animate({opacity:1}, 'slow');
	}
	else {
		jQuery.ajax({type: "POST", url: "/benutzer-fan-werden/,user,"+user_id+",,,,",
		success: function(data) {
			$('.fan').animate({opacity:0}, 'slow');
			setTimeout('addUserFan(false)', 200);
			$('.fan_count').html(parseInt($('.fan_count').html(), 10) + 1);
		}});
	}
}

function expertAnger(user_name, club_name) {
	// jQuery.ajax({type: "POST", url: "/experte-melden/,,,,,,", data: "user_name="+user_name+"&club_name="+club_name,
	// 	success: function(data) {
	// 	}});
}

function enterGroup(id) {
	jQuery.ajax({type: "POST", url: "/gruppe-beitreten/,,"+id+",,,,", data: "id=" + id,
	success: function(data) {
		
		window.location.href = '/startseite/gruppen/gruppe/,,'+id+',,,,';
		
	}});
}

function leaveGroup(id, name) {
	jQuery.ajax({type: "POST", url: "/gruppe-verlassen/,,"+id+",,,,", data: "id=" + id,
	success: function(data) {
		
		window.location.href = '/startseite/gruppen/gruppe/,,'+id+',,,,';
		
	}});
}

var fieldCopy = '';
function addFileField(first) {

	var removeLink = '<a href="#" onclick="removeSelfAndPrevious($(this),3); return false;">entfernen</a>';
	
	if(first) {
		// make a copy of html
		field = $('#filesJS').clone();
		field.find('a.tips').remove();
		field.find('p.size11').remove();
		field.find('span').remove();
		fieldCopy = field.html();
		
		$('#addfile').attr('href', '#').bind('click', function() {
			addFileField(false);
			return false;
		});
		
		$('#moreFiles').append('<br/> '+fieldCopy + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + removeLink);
	}
	else {
		$('#moreFiles').append('<br/> '+fieldCopy + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + removeLink);
	}
	
}

function removeSelfAndPrevious(element, count) {
	var i = 0;
	for (i=1; i<=count; i++) {
		element.prev().remove();
	}
	element.remove();
}

var clubFieldCopy = '';
function addClubField(first) {
	
	var removeLink = '<a href="#" onclick="removeSelfAndPrevious($(this),3); return false;">entfernen</a>';
	
	if(first) {
		// make a copy of html
		clubField = $('#clubs').clone();
		clubField.find('a.tips').remove();
		clubFieldCopy = clubField.html();
		
		$('#addclub').attr('href', '#').bind('click', function() {
			addClubField(false);
			initSuggest('club[]', true, 'club', true);
			return false;
		});
		$('#clubs').append('<br/> '+clubFieldCopy+'&nbsp;&nbsp;&nbsp;'+removeLink);
	}
	else {
		$('#clubs').append('<br/> '+clubFieldCopy+'&nbsp;&nbsp;&nbsp;'+removeLink);
	}
	
}

var fieldResultCopy = '';
function addResultRowField(first) {
	
	field = $('#results').append($('tr.addbilance_vorlage').clone().removeClass('addbilance_vorlage').show());
	field.find('input.hiddenInput').attr('value','otherData');
	
}

function club_addbilance_verifySeason() {
	seasons = [];
	hasErrors = false;
	$('#error').hide();
	error = new Array(2);
	error[0] = false;
	error[1] = false;
	
	$('#results tr:visible select.season').each(function (data) {
		
		if (this.value == '') {
			error[0] = true;
			hasErrors = true;
		}
		if (seasons[this.value] === true) {
			error[1] = true;
			hasErrors = true;
		}
		seasons[this.value] = true;
	});

	if (hasErrors) {
		$('#error').text("Überprüfe bitte Deine Eingaben.").show();
		if (error[0])
			$('#error').append("<br />Leere Saison").show();
		if (error[1])
			$('#error').append("<br />Doppelte Saison").show();
	}
	
	return hasErrors == false;
}

function checkClubs(formname, no_submit, custom) {
	
	var clubs = $('.club');
	
	window.count = 0;
	window.verified = 0;
	window.message = false;
	
	$('#clubError').hide();
	$('#clubError').html('');

	for (var i = 0; i < clubs.length; i++) {	if (clubs[i].value != '') window.count++;	}

	for (var i = 0; i < clubs.length; i++) {
		
		if (clubs[i].value == '') continue;
		
		$.post("/vereinsname-verifizieren/,,,,,,", {q: encodeURIComponent(clubs[i].value)}, function(data) {

			 if(data == "success") {
			 	window.verified++
			 } else {
				if (!window.message) {
					$('#clubError').html('Überprüfe bitte die Namen der Vereine. Mindest einer davon existiert noch nicht.');
					window.message = true;
				}
			}

			if (window.count > 0 && window.count == window.verified) {
				if (no_submit != true) {
					// alert("Jetzt schicke ich das Formular ab!");
					jQuery("#" + formname).submit();
				}
			}
			 	
		});
	}

	$('#clubError').show();

	return false;
}

function updateArea(element) {
	
	if (element.value == "") {
		$("select#area").html("<option value=''>Bitte wähle zunächst ein Bundesland aus ...</option>");
	}
	$.getJSON("/finde-fussballkreise/,county,"+element.value+",,,,", function(data){
		options = '';
		$.each(data, function(i,item){
			options+= "<option value='" + i + "'>" + item + "</option>";
			// $("<img/>").attr("src", item.media.m).appendTo("#images");
			// if ( i == 3 ) return false;
		});
		$("select#area").html(options);
	});
}

function getSubCategories(id) {
	element = $('#links_' + id);
	if (element.hasClass('empty')) {
		loader = $('#loader_' + id);
		loader.toggle();
		$.get("/finde-fotoalben/,,"+id+",,,,", function(data){
			element.html(data);
			element.toggle();
			loader.toggle();
			element.removeClass('empty');
		});
	} else {
		element.toggle();
	}
}

// e.g. for supporter board
$.fn.listScroll = function(settings) {
	
	settings = $.extend({speed: 0.8	}, settings);		
	
	var list = 'supporter_list';
	
	var offset = $('#' + list).offset().left;
	var stripWidth = 0;
	var count = 0;
	var wrapperWidth = $('#wrapper').width();
	
	var amount = 0;
	
	$('#' + list).find('img').load(function() {
		count+= 1;
		if (count == $('#' + list).find('img').length) {
			init();
		}
	});
	
	function init() {
		
		$('#' + list).find('li').each(function(i, item) {
			stripWidth+= $(this, i).width();
			$(this, i).css('width', $(this, i).width());
		});
		
		// remember the last element to be able to add disappeared elements to the chain, after the last item
		amount = stripWidth + 15;
		
		$('#' + list).css('left', '0px');

		speed = settings.speed;
		time = ($('#' + list).offset().left + amount) / speed;
		scrollLi($('#' + list), amount, time);
	}

	function scrollLi(element, amount, time) {
		
		if (time === undefined) {
			var time = Math.floor((element.offset().left + amount) / settings.speed);
		}
		
		// the target coordinate is relative to the initial position of the first element
		element.animate({left: '-' + amount + 'px'}, time, "linear", function(){

			// get new position behind last element
			new_position = wrapperWidth + 15;
			element.css('left', new_position + 'px');
			// move element
			scrollLi($('#' + list), amount);
		});

	}

	$('#wrapper').hover(
		function(){
			$(this).find('ul').stop();
		},
		function(){
			speed = settings.speed;
			time = ($('#' + list).offset().left + amount) / speed;
			scrollLi($('#' + list), amount, time);
		}
	);
};

/**
 * An autosuggest textbox control.
 * @class
 * @scope public
 */
function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, 
                            oProvider /*:SuggestionProvider*/) {
    
	if(oTextbox == null) {
		alert('Textbox not found');
	}
	
    /**
     * The currently selected suggestions.
     * @scope private
     */   
    this.cur /*:int*/ = -1;

    /**
     * The dropdown list layer.
     * @scope private
     */
    this.layer = null;
    
    /**
     * Suggestion provider for the autosuggest feature.
     * @scope private.
     */
    this.provider /*:SuggestionProvider*/ = oProvider;

    /**
     * The textbox to capture.
     * @scope private
     */
    this.textbox /*:HTMLInputElement*/ = oTextbox;
    
    //initialize the control
    this.init();
    
}

/**
 * Autosuggests one or more suggestions for what the user has typed.
 * If no suggestions are passed in, then no autosuggest occurs.
 * @scope private
 * @param aSuggestions An array of suggestion strings.
 * @param bTypeAhead If the control should provide a type ahead suggestion.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/,
                                                     bTypeAhead /*:boolean*/) {
    
    //make sure there's at least one suggestion
    if (aSuggestions.length > 0 && aSuggestions != null) {
        if (bTypeAhead) {
           this.typeAhead(aSuggestions[0]);
        }
        
        this.showSuggestions(aSuggestions);
    } else {
        this.hideSuggestions();
    }
};

/**
 * Creates the dropdown layer to display multiple suggestions.
 * @scope private
 */
AutoSuggestControl.prototype.createDropDown = function () {

    var oThis = this;

    //create the layer and assign styles
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    //this.layer.style.width = this.textbox.offsetWidth;
    
    //when the user clicks on the a suggestion, get the text (innerHTML)
    //and place it into a textbox
    this.layer.onmousedown = 
    this.layer.onmouseup = 
    this.layer.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;

        if (oEvent.type == "mousedown") {
            oThis.textbox.value = oTarget.firstChild.nodeValue;
            oThis.hideSuggestions();
        } else if (oEvent.type == "mouseover") {
            oThis.highlightSuggestion(oTarget);
        } else {
            oThis.textbox.focus();
        }
    };
    
    
    document.body.appendChild(this.layer);
};

/**
 * Gets the left coordinate of the textbox.
 * @scope private
 * @return The left coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getLeft = function () /*:int*/ {

    var oNode = this.textbox;
    var iLeft = 0;
    
    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }
    
	if($.browser.msie) {
		iLeft = iLeft + 1;
	}
    
    return iLeft;
};

/**
 * Gets the top coordinate of the textbox.
 * @scope private
 * @return The top coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getTop = function () /*:int*/ {

    var oNode = this.textbox;
    var iTop = 0;
    
    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
	if($.browser.msie) {
		iTop = iTop + 1;
	}
	
    return iTop;
};

/**
 * Handles three keydown events.
 * @scope private
 * @param oEvent The event object for the keydown event.
 */
AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {

    switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow 
            this.nextSuggestion();
            break;
        case 13: //enter
            this.hideSuggestions();
            break;
    }

};

/**
 * Handles keyup events.
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

    var iKeyCode = oEvent.keyCode;

    //for backspace (8) and delete (46), shows suggestions without typeahead
    if (iKeyCode == 8 || iKeyCode == 46) {
        this.provider.requestSuggestions(this, false);
        
    //make sure not to interfere with non-character keys
    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
    } else {
        //request suggestions from the suggestion provider with typeahead
        this.provider.requestSuggestions(this, false);
    }
};

/**
 * Hides the suggestion dropdown.
 * @scope private
 */
AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

/**
 * Highlights the given node in the suggestions dropdown.
 * @scope private
 * @param oSuggestionNode The node representing a suggestion in the dropdown.
 */
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {
    
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current"
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};

/**
 * Initializes the textbox with event handlers for
 * auto suggest functionality.
 * @scope private
 */
AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;
    
    //assign the onkeyup event handler
    jQuery(this.textbox).keyup(function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyUp() method with the event object
        oThis.handleKeyUp(oEvent);
    });
    
    //assign onkeydown event handler
     jQuery(this.textbox).keydown(function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyDown() method with the event object
        oThis.handleKeyDown(oEvent);
    });
    
    //assign onblur event handler (hides suggestions)    
    jQuery(this.textbox).blur(function () {
        oThis.hideSuggestions();
    });
    
    //create the suggestions dropdown
    this.createDropDown();
};

/**
 * Highlights the next suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
AutoSuggestControl.prototype.nextSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue; 
    }
};

/**
 * Highlights the previous suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
AutoSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur > 0) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue;   
    }
};

/**
 * Selects a range of text in the textbox.
 * @scope public
 * @param iStart The start index (base 0) of the selection.
 * @param iLength The number of characters to select.
 */
AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) {

    //use text ranges for Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iLength - this.textbox.value.length);      
        oRange.select();
        
    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }     

    //set focus back to the textbox
    this.textbox.focus();      
}; 

/**
 * Builds the suggestion layer contents, moves it into position,
 * and displays the layer.
 * @scope private
 * @param aSuggestions An array of suggestions for the control.
 */
AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) {
    
    var oDiv = null;
    this.layer.innerHTML = "";  //clear contents of the layer
    
    for (var i=0; i < aSuggestions.length; i++) {
        oDiv = document.createElement("div");
        oDiv.appendChild(document.createTextNode(aSuggestions[i]));
        this.layer.appendChild(oDiv);
    }
    
    this.layer.style.left = this.getLeft() + "px";
    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
    this.layer.style.visibility = "visible";

};

/**
 * Inserts a suggestion into the textbox, highlighting the 
 * suggested part of the text.
 * @scope private
 * @param sSuggestion The suggestion for the textbox.
 */
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
};


/**
 * Provides suggestions for state names (USA).
 * @class
 * @scope public
 */
function RemoteSuggestions(sField, minLength, region) {
    
    this.field = sField;
	this.minlength = minLength;
	this.region = region;
}

/**
 * Request suggestions for the given autosuggest control. 
 * @scope protected
 * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
 */
RemoteSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                                                          bTypeAhead /*:boolean*/) {

	if(oAutoSuggestControl.textbox.value.length >= this.minlength) {

	    $.post("/vorschlaege/,,,,,,,", {q: encodeURIComponent(oAutoSuggestControl.textbox.value), field:this.field, region:this.region}, function(data) {

			 if(data != "" && data != "null") {
			 	var aSuggestions = eval(data);
			 } else {
			 	var aSuggestions = null;
				oAutoSuggestControl.hideSuggestions();
			 }
	         oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);     
			 	
		});
	
	}
	
};

function initSuggest(name, multiple, optName, allregions) { 
	
	if(multiple) {
		fieldname = optName;
	} else {
		fieldname = name;
	}
	
	if (!allregions) {
		suggest_for_region = page;
	} else {
		suggest_for_region = 'all';
	}
	
	if(multiple) {
		var element = $('.club').get();

		for(var i = 0; i<=element.length; i++) {
			if(element[i]) {
				new AutoSuggestControl(element[i], new RemoteSuggestions(fieldname, 2, suggest_for_region));
			}
		}
	}
	else {
		var element = document.getElementsByName(name)[0];
		new AutoSuggestControl(element, new RemoteSuggestions(fieldname, 2, suggest_for_region));
	}
}

function showMap(element) {

 $('#themap').css("backgroundImage", 'url(_images/map_' + element + '.jpg)');

}

function hideMap(element) {

 $('#themap').css("backgroundImage", 'url(_images/map_' + 'raw' + '.jpg)');

}
