function onFocusSearch(element) {
  if (element.value == element.defaultValue) element.value = '';
}

function onLoad(sPathIDs) {
  setCurrentMenuItem($('#menu1 ol > li'), sPathIDs);
  setCurrentMenuItem($('#menu2 ol > li'), sPathIDs);  
}

function setCurrentMenuItem(oMenu, sPathIDs) {
  var nMenuItem = '';  
  var value;
  var aPathIDs = sPathIDs.split(',');
  
  for(var nI = (oMenu.length - 1); nI >= 0; nI-- ) {
    value = oMenu[nI];
    nMenuItem = value.className.match(/\d+/g);
    value.className = '';
    value.className = 'menu-item' + nMenuItem.toString() + ' ';
    if(nI == 0) value.className += 'first ';
    for(var i = 0;i < aPathIDs.length; i++) {
      if(aPathIDs[i] == nMenuItem)  {
        value.className += ' current';
        return;
      }
    }
  }
}

function openMenu(pageId, refNode) {
  var popup = $('#popup-menu' + pageId);
  if (!popup.length) {
    popup = document.createElement('div');
    popup.setAttribute ('id', 'popup-menu' + pageId);
    popup.className = 'popup-menu';
    $('body').append(popup);
    popup.timeout = null;
  }

  if (false && !popup.firstChild) {
    $.ajax({
      url: 'MenuEntries' + pageId + '.html',
      type: "GET",
      dataType: "html",
      success: function(html) {
        $(popup).html(html);
      }
     });
  }

  var offset = $(refNode).offset();
  offset.top += $(refNode).outerHeight(false);
  offset.left--;
  $(popup).removeClass('hidden');
  $(popup).offset(offset);

  $(popup).unbind('mouseleave mouseenter');
  $(refNode).unbind('mouseleave');
  clearTimeout (popup.timeout);

  $(refNode).bind('mouseleave', function() {
    popup.timeout = setTimeout(function() {$(popup).addClass('hidden');}, 500);
  });

  $(popup).bind('mouseenter', function() {
    clearTimeout (popup.timeout);
    $(popup).unbind('mouseleave');
    $(popup).bind('mouseleave', function() {
      popup.timeout = setTimeout(function() {$(popup).addClass('hidden').unbind('mouseleave');}, 500);
    });
  });

}

function getPreviewLink() {
    var nCardType = $('input:radio[name=CardType]:checked').val();
    var sMessage = $('#input_message').val();
    var link = document.getElementById('lightbox');

    if(nCardType > 0 && sMessage > '') {

      link.href = '?preview=1&type=' + nCardType + '&message=' + escape(sMessage);
      $('#lightbox').lightBox({
        imageLoading: 'img/lightbox/lightbox-ico-loading.gif',
      	imageBtnClose: 'img/lightbox/lightbox-btn-close.gif'
      });
      $("#lightbox").trigger('click');
    }
    else {
      link.href = '#';
      $('#lightbox').unbind();
    }
    return false;
}

function updateChars(textarea) {
  var sText = textarea.value;
  var aLines = sText.toString().split('\n');
  var eCharsLeft = document.getElementById('notifier');
  var nLines = 0;
  var nChars = 0;
  var line = 0;
  var sLine = '';
  var nLength = 0;

  // anz lines 9
  for(line in aLines) {
      sLine = aLines[line].toString();
      nLength += Math.floor(sLine.length / 28) * 28;
      nLength += (line == aLines.length-1 ? sLine.length % 28 : 28);

      nLines++;
      nLines += Math.floor(sLine.length / 28);
      nChars = sLine.length % 28;
  }
  nLines--;

  nChars = 252 - nLength;
  if(nLines > 8 || nChars <= 0) {
    eCharsLeft.innerHTML = 'Ihre Nachricht ist zu lang.';
    $('#ECardFormular input[type=submit]').attr('disabled', 'disabled');
  }
  else {
    $("#ECardFormular input[type=submit]").removeAttr("disabled");
    eCharsLeft.innerHTML = '';
  }
}


//var $j = jQuery.noConflict();
$.require('Additor/3rdParty/jquery.autocomplete.js');
$.require('Additor/3rdParty/jquery.highlight-3.yui.js');
$(document).ready(function() {
	$("#search-expr, #search-expr-header").autocomplete(
		"SearchAutoComplete.php",
		{
			minChars:3,
			autoFill:false,
			width: 180
		}
);

  var hash = $(location).attr('hash');
  if (hash) {
    hash = hash.split("highlight:");
    if (hash[1]) {
      var highlightWords = hash[1];
      highlightWords = highlightWords.split(",");
      for (highlightWord in highlightWords) {
        if (highlightWords[highlightWord]) {
          $(".section").highlight(highlightWords[highlightWord]);
        }
      }
    }
	}
});



/**
 * Funktion zum Absenden des Kalender-Filter-Formulars.
 * Weil IE Faxen macht, wird das nicht über onchange gemacht.
 * */
$().ready(function() {
	$('#CalendarControlForm').change(function() {
		$('#CalendarControlForm').submit();
	});
});


/**
 * Initialisiert das DropDown für die Bezirke bei NewEventPage.
 * Bezirke sind abhängig von ausgewählter Region.
 * @param oTarifeJSON die Tarife in JSON-Format
 * @param nSelectedBezirkID der evtl. schon vorselektierter Bezirksverband
 * */
function initBezirkeOptionList(oBezirkeJSON, nSelectedBezirkID) {
	// Bezirksverbände aktualisieren
	if ($('#Region').length) {
		updateBezirke(oBezirkeJSON, $('#Region')[0].value, nSelectedBezirkID);
	}
	
	// wird aufgerufen, wenn Region aus dem DropDown gewählt wurde
	$('#Region').change(function(param) {
		var nSelectedRegionID = param.target.value;

		// Bezirksverbände aktualisieren
		updateBezirke(oBezirkeJSON, nSelectedRegionID, nSelectedBezirkID);
	});
}

/**
 * Aktualisiert das DropDown für die Bezirksverbände bei NewEvent.
 * Es ist abhängig von der Auswahl der Region.
 */
function updateBezirke(oBezirkeJSON, nSelectedRegionID, nSelectedBezirkID) {
	// falls KinderElemente schon vorhanden --> löschen
	$('#Bezirksverband').empty();
	// einen Eintrag ("Bitte wählen...") einfügen... aber auf primitive weise,
	// weil IE primitiv ist
	var emptyOption = $("<option>Bitte wählen...</option>");
	emptyOption.val('-1');
	$('#Bezirksverband').append(emptyOption);

	// alle Bezirke durchgehen und gucken, wo oBezirk.REGIONNR ==
	// nSelectedRegionID ist
	for ( var i = 0; i < oBezirkeJSON.length; i++) {
		var oBezirk = oBezirkeJSON[i];
		if (oBezirk.REGIONNR == nSelectedRegionID) {
			// DOM-Element (option) einfügen
			// var option = new Option(oBezirk.LANGNAME, oBezirk.ORGASTELLE_NR);
			var option = $("<option>" + oBezirk.LANGNAME + "</option>");
			option.val(oBezirk.ORGASTELLE_NR);
			$('#Bezirksverband').append(option);

			// wenn Bezirksverband schon gewählt --> vorselektieren
			if (nSelectedBezirkID != -1 && nSelectedBezirkID == oBezirk.ORGASTELLE_NR) {
				$('#Bezirksverband option[value=' + nSelectedBezirkID + ']').attr('selected', 'selected');
			}
		}
	}
}

/**
 * Zeigt einen StandardText in einm InputField. Es wird gelöscht, wenn User
 * reinklickt. Wenn Fokus verloren geht und nichts drin steht, kommt wieder der
 * StandardText rein.
 * 
 * @param ID
 *            die ID des EingabeFeldes
 * @param PATTERN
 *            das Muster, was erscheinen soll, zb: "TT.MM.JJJJ" oder "Betreff"
 */
function initInputWithDefault (ID, PATTERN) {
	if (ID == null || $(ID) == null) return;
	
	// wenn Feld leer ist --> Muster anzeigen
    var inputField = $('#'+ID);
    if (!inputField.attr('value') || inputField.val() == PATTERN) {
    	inputField.attr('value', PATTERN);
    	inputField.addClass('with-pattern');
    }
    
    // wenn Feld Fokus bekommen
    inputField.focusin(function(elem) {
    	var elem = $('#'+elem.currentTarget.id);
    	// wenn noch Muster drin ist
    	if (elem.attr('value') == PATTERN) {
    		elem.attr('value', '');
    		elem.removeClass('with-pattern');
    	}
    });
    
    // wenn Feld verlassen
    inputField.focusout(function(elem) {
    	var elem = $('#'+elem.currentTarget.id);
    	// und es leer ist
    	if (elem.attr('value') == '') {
    		elem.attr('value', PATTERN);
    		elem.addClass('with-pattern');
    	}
    });
}

