/*
 *  Initializations on page load.
 */
$(document).ready(function(){
    initSearchScopeSection();
    $('#search-simple fieldset .tab-left a').add('#search-simple fieldset .tab-right a').click(handleSearchTabClick);
	$('input.submit').createLinkButton();
});


/*
 *  On the Advanced Search page there there is a section for specifying the search scope. This includes toggable 
 *  sections, dynamic drop-down menus which can be dynamically added/removed, and checkbox toggling.
 */
var $initialRemoveLink  = null;
var initialSearchSelect = null;
var searchSelectCounter = 1; // current number of selects
var searchSelectOptions = 0; // the number of options in initial select
var removeLinkTextString = "";
function initSearchScopeSection() {
	if (!$('#main #search-advanced .expanding').size()) {
		return false;
	}
	initSearchCheckboxToggle();
	
	// toggle expandable radio-button sections
	$('#main #search-advanced .expanding .form-field-wide').siblings().not('.open').hide().parent().css("paddingBottom","0");
    $('#main #search-advanced .expanding .form-field-wide input').click(function(){
        if ($(this).parent().siblings('.open').size() == 0) {
        	$(this).parent().siblings().addClass("open").show().parent().css("paddingBottom","7px");
        	$(this).parent().parent().siblings('.expanding').find('.open').removeClass("open").hide().parent().css("paddingBottom","0");
        }
        return true;
    });
	
	// init dynamic drop-down menues
	$initialRemoveLink = $('#main #search-advanced .expanding a.remove').show().click( handleRemoveLink ).parent();
	$('#main #search-advanced .expanding a.add').show().click( handleAddLink );
	
	// As Fallback, within the HTML the select menu is a multi-select menu. Just removing "multiple" and "size" attributes
	// in order to turn it into a drop-down menu, will cause non of the entries to be inititally visible. Therefore this is 
	// a workaround for this problem, where a new select Element is created and options from original are copied (Not that pretty 
	// mabey this can be improved?!).
	var multiSelect = $('#main #search-advanced .expanding select').get(0);
	var $newSelect = $(document.createElement("select"));
	$newSelect.attr("class", $(multiSelect).attr("class")).attr("id", $(multiSelect).attr("id")).attr("name", $(multiSelect).attr("name"));
	if($.browser.msie) {		
		$newSelect.append( $(multiSelect).find("option") );
	} else {		
		var optsHtml = "";
		$(multiSelect).find("option").each(function(i){
			optsHtml += "<option value='" + $(this).attr("value") + "'>" + $(this).html() + "</option>";
		});
		$newSelect.html( optsHtml );		
	} 
	$(multiSelect).parent().append($newSelect);
	$(multiSelect).remove();
	initialSearchSelect = $newSelect.get(0);		
	
	searchSelectOptions = $(initialSearchSelect).find("option").size();
}
function handleAddLink () { // handles click event of add link (supports initDynamicSearchSelects function)
	$(this).parent().before( $initialRemoveLink.clone(true) );
    $(this).parent().prev().find('a.remove').click( handleRemoveLink );
    $(this).parent().before( $(initialSearchSelect).parent().clone(true) );
    searchSelectCounter++;
    $(this).parent().prev().find('select').removeAttr("id");
    if (searchSelectCounter >= searchSelectOptions) {
        $(this).hide();
    }
    return false;
}
function handleRemoveLink () { // handles click event of remove links (supports initDynamicSearchSelects function)	
	$(this).parent().next().remove();
    $(this).parent().remove();
    searchSelectCounter--;
    if (searchSelectCounter < searchSelectOptions) {
        $('#main #search-advanced a.add').show();
    }
    if (searchSelectCounter < 1) {
		$('#main #search-advanced .expanding a.collapse').click();
    }
    return false;
}
/*
 * On the Advanced Search Page, in the section where the search scope is selected, there are a number of checkboxes specifying
 * the type of webpages to search. An "All" checkbox is added dynamically, which toggles the checks of all the other checkboxes.
 */
function initSearchCheckboxToggle() {
	var $all = $('#search-scope input.all');
	$all.get(0).checked = true;
	$all.click( function(){
		this.checked = true;
		var targetToggle = this.checked;
		$(this).parent().siblings().find('input').each(function(i){
			this.checked = false;
		});
	}).parent().siblings().find('input').click( function(){
		if(this.checked) {
			$('#search-scope input.all').get(0).checked = false;
		} else {
			var otherChecked = false;
			$(this).parent().siblings().find('input').not('.all').each(function(i){
				if(this.checked) {
					otherChecked = true;
				}
			});
			if(!otherChecked) {
				$('#search-scope input.all').get(0).checked = true;
			}
		}
	});
}


/*
 * In the HTML Prototype on the startpage there is a yellow search box
 * in the right margin. Clicking on a tab changes the highlighted tab and
 * changes the scope of the search (by setting value attribute of input field
 * to either "network" or "internal").
 */
function handleSearchTabClick(e) {
    var $this = $(this);
    var $selected = $(this).parent().siblings('p.selected');
    var linkText = $(this).text();
    var linkText2 = $selected.text();
    
    var $headline  = $(this).parent().parent().find('h4');
    var $paragraph = $(this).parent().parent().find('p.desc');
    
    $this.parent().html(linkText).addClass('selected');
    $selected.removeClass('selected').html("<a href='#'>" + linkText2 + "</a>");
	
    // swap URL of "profi-suche" link, headline, and text when tabs are switched; the variables
    // "altExtendedSearchURL", "altHeadline", and "altText" should
    // be definied on the HTML page per inline javascript variable
    var $extendedURL = $this.parent().parent().find('li a.extended-search');
    var newExtendedSearchURL = (typeof altExtendedSearchURL != "undefined") ? (altExtendedSearchURL) : $extendedURL.attr("href");
    altExtendedSearchURL = $extendedURL.attr("href");
    $extendedURL.attr("href",newExtendedSearchURL);
    
    var newAltHeadline = (typeof altHeadline != "undefined") ? (altHeadline) : "";
    altHeadline = $headline.text();
    $headline.html(newAltHeadline);
    
    var newAltText = (typeof altText != "undefined") ? (altText) : "";
    altText = $paragraph.text();
    $paragraph.html(newAltText);

    var $input = $('#search-simple fieldset input[@name=command]');
    if ($('#search-simple fieldset p.selected').attr("class").indexOf('left') != -1) {
        $input.val('network');
    } else {
        $input.val('internal');
    }

    $('#search-simple fieldset .tab-left a').add('#search-simple fieldset .tab-right a').click(handleSearchTabClick);
    return false;
}
/*
 * 
 */
$.fn.extend({
	createLinkButton: function(s){
		s = $.extend({
			hiddenClass: 'aural',
			focusClass: 'focused'
		}, s);
		return this.each(function(){
			var $this = $(this);
			var id = $this.attr('id');
			var $label = $('label[for=' + id + ']:first');
			var labelVal = $label.html();
			var classnames = this.className;
			$label.html('<span><span><span><span>' + labelVal + '</span></span></span></span>');
			if ($this.is('[type=radio]')) {
				$this.addClass(s.hiddenClass).focus(function(){
					$label.addClass(s.focusClass);
				}).blur(function(){
					$label.removeClass(s.focusClass);
				});
				$label.click(function(){
					var $this = $(this);
					var iID = $this.attr('for');
					$('#' + iID).attr({
						checked: 'checked'
					});
					$(this).parents('form:first').trigger('submit');
					return false;
				}).addClass(classnames);
			} else {
				var val = $this.val();
				id = (id) ? 'id=' + id : '';
				var link = $this.after('<a href="#" ' + id + ' class="' + classnames + '"><span class="aural">' + val + '</span></a>').next('a');
				link.click(function(){
					$(this).ancestors('form:first')[0].submit();
					return false;
				}).end().remove();
			}
			
		});
	}
});
