/* ---- common ---- */
/****************************/
/* Common utility functions */
/****************************/
/* bugfix for IE6 - reloading background images on mouse over */
try
{	document.execCommand('BackgroundImageCache', false, true);
}
catch(ex)
{
}

/*
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
*/
/* Find the position of a DOM Element */

function findPosition(obj) {
	var curleft = 0;
    var curtop = 0;
    if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft, curtop];      
}

/* Get the scroll offset of the window */

function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
}

function cancelBubbling(e) {
  if (!e) {
    var e = window.event
  }
  e.cancelBubble = true
  if (e.stopPropagation) {
    e.stopPropagation()

  }
}

/************************/
/* Global DOM Functions */
/************************/

/* Search for parents node by tagname */
function findParentNodeByTagName(obj, tagName) {

	do {
		obj = obj.parentNode;
	}  while (obj.nodeName != tagName && obj.nodeName != 'BODY')

	return (obj)
}

/* Search parents for element with specific classname */
function findParentNodeByClassName(obj, className) {

	do {
		obj = obj.parentNode;
	}  while ((obj.className.indexOf(className) == -1) && obj.nodeName != 'BODY')

	return (obj)
}

/* Search children for element(s) with specific classname */
function getElementsByClassName(obj, className, looseSearch) {
    /*
    obj = the object to search from;
    classname = the name of the class to search for;
    looseSearch = (default:true), if true then use indexOf ; if false then strict compare;
    */

    var list = new Array();
    var childrenList = obj.getElementsByTagName('DIV');
    var searchCriterium;

    if(!looseSearch)
        searchCriterium = "childrenList[i].className == className";
    else
        searchCriterium = "childrenList[i].className.indexOf(className) != -1";

    for(var i=0; i < childrenList.length; i++) {
        if(eval(searchCriterium)) {
            list.push(childrenList[i]);
            }
    }
    return (list);
}

/************************/
/* More specific Functions */
/************************/

function mailAuthor(obj) {
	var form = obj.parentNode;
	var msg = "";

	if (form.Leserbrief.value == '' && !form.Leserbrief.value) {
		msg = msg + "<li>Das Feld 'Leserbrief' muss ausgefüllt werden.</li>";
	}
	if (form.Name.value == '' && !form.Name.value) {
		msg = msg + "<li>Das Feld 'Ihre Name' muss ausgefüllt werden.</li>";
	}
	if (form.Absender.value == '' && !form.Absender.value) {
		msg = msg + "<li>Das Feld 'E-Mail Absender' muss ausgefüllt werden.</li>";
	}
	if (form.Website.value == '' && !form.Code.value) {
		msg = msg + "<li>Das Feld 'Code' muss ausgefüllt werden.</li>";
	}
	if (msg != '') {
		var errdiv = document.getElementById("formErrors");
		var ul = document.createElement("ul");
		ul.innerHTML = msg;
		if(errdiv.firstChild) {errdiv.removeChild(errdiv.firstChild)}	// Clean the error div
		errdiv.appendChild(ul);
		alert('false')
		return false;
	}
	form.submit();
	return false;
}

function switchTab (theObj) {
    /* first check if object is already active */
    if(findParentNodeByTagName(theObj, 'LI').className.indexOf('active') != -1) {
        return false;
    }

    /* root element of the tabs container */
    var tabsContainerObj = findParentNodeByClassName(theObj, 'tabbedPanes');
    /* root element of the tabs group */
    var tabsObj = findParentNodeByClassName(theObj, 'tabs');

    /* list of tab buttons */
    var tabItems = findParentNodeByClassName(theObj, 'tabs').getElementsByTagName('A');
    /* list of tab panes */
    var paneList = getElementsByClassName(tabsContainerObj, 'pane', true);

    /* find out the order number of the selected tab */
    var position;

    for (var i=0; i < tabItems.length; i++ ) {
        if (tabItems[i] == theObj) {
            position = i;
            findParentNodeByTagName(tabItems[i], 'LI').className = 'active';
            //theObj.parentNode.className = 'active';
            //alert(theObj.nodeName + "==");
        }
        else {
            findParentNodeByTagName(tabItems[i], 'LI').className = '';
            //alert(theObj.nodeName);
        }
    }

    for (var i=0; i < paneList.length; i++ ) {
        if (i == position) {
            paneList[i].className += ' active';
        }
        else {
            paneList[i].className = paneList[i].className.replace(' active','');
        }
    }
}

function openPopUp (url,w,h,t,l,s,r) {
  myWindow = window.open(url, 'popupWindow', "width="+w+",height="+h+",left="+l+",top="+t+",scrollbars="+s+",resizable="+r+", status=no");
  myWindow.focus();
}

/* ---- cookies ---- */
/* STATUS: FINAL */

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
/* ---- styleswitcher ---- */
/*
STATUS: PENDING
TODO: this code was written in ms-write or something because the eol are not standard. 
*/

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}
function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}
function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}
window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}
window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);

/* ---- modules ---- */
/*
STATUS: PENDING
TODO: Test Richmedia (just integrated)
*/

/*
	This file contains all the javascripts that are used by the modules section in the welt online site
*/

/*
	Javascript functions for the poll forum
*/
function ShowHide( id)
{
  try{
	var hideId = "vote-"+id;
	var showId = "voted-"+id;
	var hideElm = document.getElementById( hideId);
	var showElm = document.getElementById( showId);

	if ( hideElm != null && showElm != null) {
		hideElm.style.display = "none";
		showElm.style.display = "block";
	}
	var hideId = "vote-"+id+"-art";
	var showId = "voted-"+id+"-art";

	var hideElm = document.getElementById( hideId);
	var showElm = document.getElementById( showId);

	if ( hideElm != null && showElm != null) {
		hideElm.style.display = "none";
		showElm.style.display = "block";
	}

  }catch (erm){
	//alert("peiling.ShowHide()"+erm);
  }
}
function initialHide( id)
{
  try
  {
	//hide poll Q&A and show Results
	var mentometer = readCookie("mentometer");
	if ( mentometer != null )
	{
	  var mentometer_array = mentometer.split("M");
	  for ( i = 0; i < mentometer_array.length; i++ )
	  {
		if ( mentometer_array[i] != 'null' )
		{
		  if ( mentometer_array[i].match(id) )
		  {
			  ShowHide(""+id);
		  }
		}
	  }
	}
  }
  catch ( erm )
  {
	alert("displayPoll" + erm);
  }
}
/*
	end Javascript functions for the poll forum
*/



/*
 *	Start function for tabs
 */



var TabHash = {};

function showTab(tabgroup, panelid, islasttab)
{	//alert("showTab " + tabgroup + " " + panelid + " " + islasttab);
	/* First check if there's 1 tab selected (the first time its the 1st tab probably) */
	if (TabHash[tabgroup])
	{
		// If the selected tab is the lasttab 
		if (TabHash[tabgroup][2]){
			// Set a different deselect-style 
			TabHash[tabgroup][0].className="unselectedtablast";
		}else{
			// If not, set the default deselect-style
			TabHash[tabgroup][0].className="unselectedtab";
		}
		TabHash[tabgroup][1].style.display= "none";
	}
	/* Then remember the new selected Tab and remember if the tab is the lasttab (islasttab boolean) */
	TabHash[tabgroup] = [document.getElementById(tabgroup + "_" + panelid + "_tab"), document.getElementById(tabgroup + "_" + panelid), islasttab];
	TabHash[tabgroup][0].className="selected"; 
	TabHash[tabgroup][1].style.display = "block";
	/* If select tab is the last tab, show 'padding-line' */
    /* deactivated - not needed in new layout */

/*	if(islasttab){
		document.getElementById('tablastend').style.visibility = 'visible';
	}else{
		document.getElementById('tablastend').style.visibility = 'hidden';
	}
*/
}

/*
 *	End function for tabs
 */

/*
 *	Start function for slideshows
 */


var SlideHash = {};

function slide(slidegroup,delta)
{
	i=0;
	if (SlideHash[slidegroup])
	{
	if (!delta) return true;
		i = SlideHash[slidegroup][0] + (delta>0 ? 1 : -1);
		SlideHash[slidegroup][1].style.display="none";
	}

	//check to see if there if buttons still needs to be displayed
	if (document.getElementById(slidegroup + "_" + (i+1)) != null) document.getElementById(slidegroup + "_forward").style.visibility = "visible";
	else document.getElementById(slidegroup + "_forward").style.visibility = "hidden";

	if (document.getElementById(slidegroup + "_" + (i-1)) != null) document.getElementById(slidegroup + "_back").style.visibility = "visible";
	else document.getElementById(slidegroup + "_back").style.visibility = "hidden";

	SlideHash[slidegroup] = [i,document.getElementById(slidegroup + "_" + i)];
	SlideHash[slidegroup][1].style.display="block";
	return true;
}

/*
 *	End function for slideshows
 */


/*
 *	TabEx used for richmedia box
 */

var LOADED = false;
var hash_tab_ex = {};

function setTabInfo(groupid, nrtabs,cn_notsel, cn_sel, cn_first, cn_last, cn_stop, cn_stop_br)
{
        hash_tab_ex[groupid] = {};
        hash_tab_ex[groupid]["classNotSelected"] = cn_notsel;
        hash_tab_ex[groupid]["classSelected"] = cn_sel;
        hash_tab_ex[groupid]["classFirst"] = cn_first;
        hash_tab_ex[groupid]["classLast"] = cn_last;
        hash_tab_ex[groupid]["classStop"] = cn_stop;
        hash_tab_ex[groupid]["classStopBr"] = cn_stop_br;

        hash_tab_ex[groupid]["nrTabs"] = nrtabs;
        hash_tab_ex[groupid]["currentTabNr"] = -1;
}

function addFirstLast(groupid,sel)
{
        result = "";
        prefix = "";

        if (sel) prefix = hash_tab_ex[groupid]["classSelected"] + "_";
        else prefix = hash_tab_ex[groupid]["classNotSelected"] + "_";

        if (hash_tab_ex[groupid]["currentTabNr"] == 0) return " " + prefix + hash_tab_ex[groupid]["classFirst"];
        if (hash_tab_ex[groupid]["nrTabs"] == hash_tab_ex[groupid]["currentTabNr"]+1) return  " " + prefix + hash_tab_ex[groupid]["classLast"];
        return "";
}

function isLastTab(groupid)
{
        return (hash_tab_ex[groupid]["nrTabs"] == hash_tab_ex[groupid]["currentTabNr"]+1);
}

function showTabEx(groupid, tabid, tabnr)
{
        if (!document.getElementById(groupid+"_"+tabid)) return false;;
        if (!hash_tab_ex[groupid]) return false; // not initialized;

        if (hash_tab_ex[groupid]["currentTabNr"] != -1)
        {
                unsel = hash_tab_ex[groupid]["classNotSelected"] + addFirstLast(groupid,false);
                hash_tab_ex[groupid]["currentTabObj"].className = unsel;
                hash_tab_ex[groupid]["currentDivObj"].style.display = "none";
        }

        tabobj = document.getElementById(groupid + "_" + tabid + "_tab");
        divobj = document.getElementById(groupid + "_" + tabid);

        hash_tab_ex[groupid]["currentTabNr"]  = tabnr;
        hash_tab_ex[groupid]["currentTabObj"] = tabobj;
        hash_tab_ex[groupid]["currentDivObj"] = divobj;

        sel = hash_tab_ex[groupid]["classSelected"] + " " + addFirstLast(groupid,true);

        tabobj.className = sel;
        divobj.style.display = "block";

        stop = document.getElementById(groupid + "_stop_tab");
        if (stop) stop.className = (isLastTab(groupid) ? hash_tab_ex[groupid]["classStopBr"] : hash_tab_ex[groupid]["classStop"]);

        return false;
}

function startupRichmedia(divarray, tabhash)
{
	setTabInfo("rmtab", divarray.length, "tab", "tab_selected","firsttab","lasttab","rest","rest break");
	tabhash = tabhash.substring(1);
	var index = -1;

	//hide all tabs and find the id of the to be selected tab
	for (i=0; i<activeTabs.length; i++)
	{
		document.getElementById("rmtab_" + activeTabs[i]).style.display = "none";
		if (tabhash && (activeTabs[i] == tabhash)) index = i;
	}

	//select a tab
	showTabEx("rmtab",activeTabs[0],0);
	if (index >=0)
	{
		showTabEx("rmtab",tabhash,index);
	}
}

/*
 *	End of TabEx
 */

currElem = null;
currElem2 = null;
function showArticleInteraction(id)
{

        if (currElem != null)
        {
                currElem.style.display = "none";
        }
        if (currElem2 != null)
        {
                currElem2.style.display = "none";
        }

        if (id == "comment")
        {
        	if (document.getElementById("readcomments")) {
                	currElem2 = document.getElementById("readcomments");
                	currElem2.style.display = "block";
                }
        }
        if (!document.getElementById(id)) return true;

		if (captcha = document.getElementById(id + "_captcha_img"))
		{
			captcha.src="/captcha/captcha.jpg?no_cache=" + Math.floor(Math.random() * 9000000 + 1000000);
		}

        currElem = document.getElementById(id);
        currElem.style.display = "block";
        return true;
}

function popupImage(id)
{
        window.open("?service=ImagePopup&id=" + id, "", "scrollbars=no, addressbar=no,statusbar=no, menubar=no");
}


function initByHash()
{	
	if (document && document.location && document.location.hash)
	{	switch (document.location.hash)
		{
			case "#article_mailauthor":
				showArticleInteraction("mailAuthor");
				break;
			case "#article_recommend":
				showArticleInteraction("recommend");
				break;
			case "#article_comment":
				showArticleInteraction("comment");
				break;
			case "#read_comments":
				showArticleInteraction("comment");
				document.location.hash="#article_readcomments";
				break;
			case "#msg_mailAuthor":
				document.getElementById("xmsg_mailAuthor").style.display = "block";
				break;
			case "#msg_comment":
				document.getElementById("xmsg_comment").style.display = "block";
				break;
			case "#msg_recommend":
				document.getElementById("xmsg_recommend").style.display = "block";
				break;
					
			//Recommend
			case "#article_recommend_parameterError":
				showArticleInteraction("recommend");
				addNotification("recommend_form","Falscher Parameter");
				document.location.hash = "#article_recommend";
				break;
			case "#article_recommend_parameterEmpty":
				showArticleInteraction("recommend");
				addNotification("recommend_form","Falscher Parameter");
				document.location.hash = "#article_recommend";
				break;
			case "#article_recommend_captcha_failure":
				showArticleInteraction("recommend");
				addNotification("recommend_form","Bitte geben Sie den Code erneut ein");
				document.location.hash = "#article_recommend";
				break;
			case "#article_recommend_captcha_sessionError":
				showArticleInteraction("recommend");
				addNotification("recommend_form","Zeitlimit abgelaufen");
				document.location.hash = "#article_recommend";
				break;
				
			//MailAuthor
			case "#article_mailauthor_parameterError":
				showArticleInteraction("mailAuthor");
				addNotification("mailAuthor_form","Falscher Parameter");
				document.location.hash = "#article_mailauthor";
				break;
			case "#article_mailauthor_parameterEmpty":
				alert('article_mailauthor_parameterEmpty');
				showArticleInteraction("mailAuthor");
				addNotification("mailAuthor_form","Falscher Parameter");
				document.location.hash = "#article_mailauthor";
				break;
			case "#article_mailauthor_captcha_failure":
				showArticleInteraction("mailAuthor");
				addNotification("mailAuthor_form","Bitte geben Sie den Code erneut ein");
				document.location.hash = "#article_mailauthor";
				break;
			case "#article_mailauthor_captcha_sessionError":
				showArticleInteraction("mailAuthor");
				addNotification("mailAuthor_form","Zeitlimit abgelaufen");
				document.location.hash = "#article_mailauthor";
				break;
					
			//Comment
			case "#article_kommentar_parameterError":
				showArticleInteraction("comment");
				addNotification("com.escenic.forum.struts.presentation.PostingForm","Falscher Parameter");
				document.location.hash = "#article_comment";
				break;
			case "#article_kommentar_captcha_failure":
				showArticleInteraction("comment");
				addNotification("com.escenic.forum.struts.presentation.PostingForm","Bitte geben Sie den Code erneut ein");
				document.location.hash = "#article_comment";
				break;
			case "#article_kommentar_captcha_sessionError":
				showArticleInteraction("comment");
				addNotification("com.escenic.forum.struts.presentation.PostingForm","Zeitlimit abgelaufen");
				document.location.hash = "#article_comment";
				break;
			case "#article_kommentar_forum_succes":
				/* firstPostInformation is not written anymore
				try{
					document.getElementById("firstPostInformation").style.display = "block";
				}catch(err){
					// "firstPostInformation" not found, not the first post on this article
				}
				*/
				//showArticleInteraction("comment");
				showArticleInteraction("comment");
				addNotification("com.escenic.forum.struts.presentation.PostingForm","Vielen Dank für Ihren Kommentar. Er wird in wenigen Minuten unter dem Artikel erscheinen.");
				document.location.hash="#article_readcomments";
				break;
			case "#article_kommentar_forum_error":
				showArticleInteraction("comment");
				addNotification("com.escenic.forum.struts.presentation.PostingForm","Falscher Parameter");
				document.location.hash="#article_comment";
				break;
			case "#article_kommentar_forum_cancel":
				showArticleInteraction("comment");
				addNotification("com.escenic.forum.struts.presentation.PostingForm","Abgebrochen");
				document.location.hash="#article_comment";
				break;


		}
		//this is needed because when this is called the page has already scrolled to the anchor, and if the content after the page is smaller
		//after the anchor then the page it will scroll to the bottom, after which the div is displayed. The div will then not be scrolled
		//into view correctly. This will recall the anchor after the div is displayed, just like the links in the menu do.
		document.location.hash = document.location.hash;
	}

}

/*
 *	Following function is used to underline every element in a mouse over over en exklusiv item
 */



function styleChildren(obj, elem, val)
{
	par = obj;
	for (i=0; i<par.childNodes.length; i++)
	{
		v = "par.childNodes[i].style." + elem + " = \"" + val + "\"";
		try { eval(v); }
		catch (e) {}
	}
}


/*
 *	end underline styleChildren
 */

/* ---- validateForm ---- */
/* STATUS:FINAL */

var forms = {};

/*	
	Add required fields to a form (by formname) and validate before submit
	----------------------------------------------------------------------
	formid -> the id of the form
	fields -> an array containing the ids of the fields that are required
	fieldnames -> an array containing the names of the fields, how they are displayed in the warning

	there should be a %formname%_alert div that can hold the warning list (ul)
	it should be like:
	
	<form name="someform" id="someform" method="post">
		required - Field 1: <input id="req" name="req"/><br/>
		not required - Field 2: <input id="req" name="notreq"/><br/>
	</form>
	<a href="#" onclick="submitForm('someform')">
	<div id="someform_alert"></div>

	<script>
		addLoadEvent(
			function() {
				addForm("someform",
				        new Array("req"),
				        new Array("Field 1")
				);
			}
		);
	</script>
*/

function addForm(formid, fields, fieldnames)
{
  forms[formid] = new Array(fields, fieldnames);
}



function addNotification(formid, notification)
{
	alertDiv = document.getElementById(formid + "_alert");
	if (!alertDiv.firstChild)
	{
		//there is no UL yet
		ul = document.createElement("ul");
		alertDiv.appendChild(ul);
	}
	li = document.createElement("li");
	li.innerHTML = notification;
	alertDiv.firstChild.appendChild(li);
}

function submitForm(formid)
{
	form = document[formid];
	fields = forms[formid][0];
	fieldnames = forms[formid][1];
	
	error = "";
	
	for (i=0; i<fields.length; i++)
	{
		fid   = fields[i];
		fname = fieldnames[i];
	
		field = form[fid];
		
		if (!field || field.value == '')
		{
			error = "Das Feld '" + fname + "' muss ausgefüllt werden.";
			addNotification(formid, error);
		}
	}
	if (error) return false;

	//if (error != '')
	//{
	//	alertdiv = document.getElementById(formid + "_alert");
	//	ul = document.createElement("ul");
	//	ul.innerHTML = error;
	//	if (alertdiv.firstChild) alertdiv.removeChild(alertdiv.firstChild);
	//	alertdiv.appendChild(ul);
	//	return false;
	//}
	form.submit();
	return false;
}

















































































/* Limitz */

/* ---- picturebars ---- */
/*
STATUS: CHECKED
TODO: maybe add some comments
*/


function imageObject() {
    this.htmlContent = "";
	/* htmlContent replaced by: */
    this.imageUrl = "";
    this.imageWidth = "";
    this.imageHeight = "";
    this.articleId = "";

    this.targetUrl = "";
	this.clickAction = "";
}

function setSelectedGallery(galleryID,numberOfImages){
	selectedGalleryID = galleryID
	n=0;
	populateGallery(selectedGalleryID,numberOfImages)
}

function nextFour(articleID,numberOfImages) {
	n+=numberOfImages
	populateGallery(articleID,numberOfImages);
}

function previousFour(articleID,numberOfImages) {
	if(n>0) {
		n-=numberOfImages
		populateGallery(articleID,numberOfImages);
	}
}

function populateGallery(articleID,numberOfImages){
    var imageObjectDOM;
    var compatabilityMode = false;

    for(var i=0;i<numberOfImages;i++){

        if(i == 0){
			if(n == 0){
				document.getElementById("picturebarBack").style.visibility="hidden";
			}else{
				document.getElementById("picturebarBack").style.visibility="visible";

			}
		}else if(i == (numberOfImages-1)){
			if((n+numberOfImages) < foto[articleID].length){
				document.getElementById("picturebarForward").style.visibility="visible";
			}else{
				document.getElementById("picturebarForward").style.visibility="hidden";
			}
		}

		try
		{

            if(foto[articleID][n+i].htmlContent == "false") {
                //Only used for frontpage
                //Get reference to image object inside the foto hyperlink

                imageObjectDOM = document.getElementById("foto" + i).getElementsByTagName("IMG")[0];

                imageObjectDOM.ImageObjectRef = foto[articleID][n+i]; // Copy reference from ImageObject to DOM IMG object
                imageObjectDOM.src = foto[articleID][n+i].imageUrl;
                imageObjectDOM.width = foto[articleID][n+i].imageWidth;
                imageObjectDOM.height = foto[articleID][n+i].imageHeight;

                //attach the mouse-events to the image object
                imageObjectDOM.onmouseover = function () { showTextPopup(this,'top','outside','medium',false,eval(this.ImageObjectRef.articleId)); };
                imageObjectDOM.onmouseout = function () { hideTextPopup(this); }

                compatabilityMode = false;
            }
            else  {
                //Backward compatibility with picturebar in premiumchannel
                document.getElementById("foto" + i).innerHTML = foto[articleID][n+i].htmlContent;
                compatabilityMode = true;
            }

            var clickActionVar = foto[articleID][n+i].clickAction;

			if(foto[articleID][n+i].targetUrl != ""){
				document.getElementById("fotoLink" + i).href = foto[articleID][n+i].targetUrl;
			}

            if(clickActionVar) {
                if (window.attachEvent) {
                     document.getElementById("fotoLink" + i).onclick = function attachedEvent() { eval(clickActionVar); };
                } else {
                    document.getElementById("fotoLink" + i).setAttribute("onClick", foto[articleID][n+i].clickAction);
                }
            }

            document.getElementById("fotoLink" + i).style.visibility = 'visible';

		}
		catch(err)
		{
            document.getElementById("fotoLink" + i).style.visibility = 'hidden';
            document.getElementById("fotoLink" + i).href = "";
            document.getElementById("fotoLink" + i).onclick = "";

            if(compatabilityMode)
                document.getElementById("foto" + i).innerHTML = "";

        }
	}
}

function switchTabsPictureBar(obj) {
	tabsObj = findParentNodeByTagName(obj, "UL");
	checkObj = findParentNodeByTagName(obj, "LI");

	for (i=0; i<tabsObj.childNodes.length; i++) {

		if(checkObj == tabsObj.childNodes[i])
			tabsObj.childNodes[i].className = 'selected';
		else
			tabsObj.childNodes[i].className = '';
	}
}
/* ---- mediabox ---- */
/*********************/
/* Mediabox functions */
/*********************/

/* Mediabox Object */
function MediaBox (DOMObject) {
	this.DOMObject = DOMObject;
	this.tabs = new Array(); // Array of DOM HTML Elements
	this.panes = new Array(); // Array of MediaBoxPane Objects
	this.activePane = 0;
	this.activeSlide = 0;
	this.previousButton = null; //DOM HTML Element
	this.nextButton = null; //DOM HTML Element
	this.initialized = false;
}

/* Pane Object inside Mediabox */
function MediaBoxPane (DOMObject) {
	this.DOMObject = DOMObject;
	this.slides = new Array();
}

/* Slide Object inside pane */
function MediaBoxPaneSlide (DOMObject) {
	this.DOMObject = DOMObject;
}

/* Initialize Mediabox (on page load) */
function mediaBoxInitialize(theObj) {
	/* If Mediabox was already initialized, skip this routine */

    if((theObj.mediaBoxObject != null) || (theObj.nodeName == "BODY"))
        return false;

    /* Make array of panes */
	try {
		// Instantiate new MediaBox object
		var theMediaBox = new MediaBox(theObj);
		theObj.mediaBoxObject = theMediaBox; // Make reference to Mediabox Object from DOMElement

		/* Add attribute "mediaBoxObject" to all child elements of the Mediabox */
		var allChildren = theObj.getElementsByTagName("*");
		for(var i in allChildren)
			allChildren[i].mediaBoxObject = theMediaBox;

		/* Get navigationbuttons (previous, next) */
		theMediaBox.previousButton = getElementsByClassName(theObj, "mediaBoxPaneNavigationPrevious", false)[0];
		theMediaBox.nextButton = getElementsByClassName(theObj, "mediaBoxPaneNavigationNext", false)[0];

		/* Get all the tabs */
		//Get container object of the tabs
		var tabContainer = getElementsByClassName(theObj, "mediaBoxTabStrip", true)[0];
		//Get List of items in that container
		var itemList = getElementsByClassName(tabContainer, "mediaBoxTab", true);
		for(i in itemList)
			theMediaBox.tabs[i] = itemList[i];

		/* Get all panes and slides */
		//Get container object with the picture panes(tabs) and slides
		var paneContainer = getElementsByClassName(theObj, "mediaBoxPaneContainer", true)[0];
		//Get List of items in that container
		var itemList = getElementsByClassName(paneContainer, "mediaBoxPane", true);

		var theMediaBoxPane;
		var theMediaBoxPaneSlide;

		for(i in itemList) {
			switch(itemList[i].className) {
				case "mediaBoxPane":
					theMediaBoxPane = theMediaBox.panes[theMediaBox.panes.length] = new MediaBoxPane(itemList[i]);
					break;

				case "mediaBoxPaneActive":
					theMediaBoxPane =  theMediaBox.panes[theMediaBox.panes.length] = new MediaBoxPane(itemList[i]);
					theMediaBox.activePane = theMediaBox.panes.length - 1;
					break;

				case "mediaBoxPaneSlide":
					theMediaBoxPaneSlide = theMediaBoxPane.slides[theMediaBoxPane.slides.length] = new MediaBoxPaneSlide(itemList[i]);
					break;

				case "mediaBoxPaneSlideActive":
					theMediaBoxPaneSlide = theMediaBoxPane.slides[theMediaBoxPane.slides.length] = new MediaBoxPaneSlide(itemList[i]);
					theMediaBox.activeSlide = theMediaBoxPane.slides.length - 1;
					break;
			}
		}
	}
	catch(error) {
		alert("Error during initialization of Mediabox [initializeMediaBox()]\n\nError Code: " + error);
		return false;
	}

	mediaBoxRefreshNavigation(theMediaBox);

	theMediaBox.initialized = true;
	return true;
}

function mediaBoxRefreshNavigation(mediaBox) {

    var maxActiveSlides = mediaBox.panes[mediaBox.activePane].slides.length;

	if(mediaBox.activeSlide == 0)
		mediaBox.previousButton.style.visibility = "hidden";
	else
		mediaBox.previousButton.style.visibility = "visible";

	if ((mediaBox.activeSlide + 1) == maxActiveSlides)
		mediaBox.nextButton.style.visibility = "hidden";
	else
		mediaBox.nextButton.style.visibility = "visible";

	return true;

}

/* Select the  pane corresponding to the tab  */
function mediaBoxPaneSelect(theObj) {
	var mediaBox;

    /* Instantiate Mediabox Object if needed */
	if(!theObj.mediaBoxObject) {
        // Find the mediaBox Rool element by moving up the DOM Tree
		mediaBox = theObj;
		do {
			mediaBox = findParentNodeByClassName(mediaBox, "mediaBox");
        }  while ((mediaBox.className != "mediaBox") && (mediaBox.className.indexOf("mediaBox ") == -1) && (mediaBox.nodeName != 'BODY')) //Find classnames exactly equal or in combination with other classname (i.e. class="Mediabox Frontpage")

        mediaBoxInitialize(mediaBox);
	}

	mediaBox = theObj.mediaBoxObject; // Use reference of the DOMElement to the Picturbar Object

	/* Find the right tab number */
	for(var i in mediaBox.tabs) {
		if(mediaBox.tabs[i].getElementsByTagName("A")[0] == theObj)
			break;
	}

	if(mediaBox.activePane == i) //If this pane is already active, exit function
		return false;

	/* Set active tab  */
	mediaBox.tabs[mediaBox.activePane].className = "mediaBoxTab";
	mediaBox.tabs[i].className = "mediaBoxTabActive";

	/* Set active pane and slide to normal */
	mediaBox.panes[mediaBox.activePane].DOMObject.className = "mediaBoxPane";
	mediaBox.panes[mediaBox.activePane].slides[mediaBox.activeSlide].DOMObject.className = "mediaBoxPaneSlide";

	/* Display chosen pane  and first slide  */
	mediaBox.panes[i].DOMObject.className = "mediaBoxPaneActive";
	mediaBox.panes[i].slides[0].DOMObject.className = "mediaBoxPaneSlideActive";
	mediaBox.activePane = i;
	mediaBox.activeSlide = 0;

	mediaBoxRefreshNavigation(mediaBox);
	return true;
}

function mediaBoxMoveSlide(theObj, direction) {
	var mediaBox;
	var currentPane;
	var maxpossibleSlides;
	var slideTest;

	/* Instantiate Mediabox Object if needed */
	if(!theObj.mediaBoxObject) {
		// Find the mediaBox Rool element by moving up the DOM Tree
		mediaBox = theObj;
		do {
			mediaBox = findParentNodeByClassName(mediaBox, "mediaBox");
        }  while ((mediaBox.className != "mediaBox") && (mediaBox.className.indexOf("mediaBox ") == -1) && (mediaBox.nodeName != 'BODY')) 
		//Find classnames exactly equal or in combination with other classname (i.e. class="Mediabox Frontpage")

		mediaBoxInitialize(mediaBox);
	}

	mediaBox = theObj.mediaBoxObject; // Use reference of the DOMElement to the Picturbar Object
	currentPane = mediaBox.panes[mediaBox.activePane];
	maxpossibleSlides = currentPane.slides.length;

	/*Test if it is possible to navigate */
	slideTest = mediaBox.activeSlide + direction;
	if((slideTest < 0) || (slideTest == maxpossibleSlides))
		return false;

	/* Hide current slide and show next */
	currentPane.slides[mediaBox.activeSlide].DOMObject.className = "mediaBoxPaneSlide";
	mediaBox.activeSlide += direction;
	currentPane.slides[mediaBox.activeSlide].DOMObject.className = "mediaBoxPaneSlideActive";

	mediaBoxRefreshNavigation(mediaBox)
	return true;
}
/* ---- popups ---- */
/********************************************/
/* Javascript textpopup with shaded corners */
/********************************************/

/* Declare some global variables, that will be persisted across the mouseover events */

var popupWindowObj; /* pointer to textPopupWindow object */
var textPopupActive = false;
var textPopupActiveOject = null;
var textPopupActiveValign;
var textPopupActivePosition;
var textPopupActiveSize;
var textPopupActiveFollow;

/*
    This function inserts the popup div at the end of the document and is then reused
*/

function insertTextPopupIntoDOM (){
    var textPopupHTML = new Array
    (
    '<div id="textPopupWindow" class="textPopup textPopupSizeSmall" onmouseover="showTextPopup(this,\'\',\'\',\'\');" onmouseout="hideTextPopup(this);">',
    '<iframe id="textPopupIframeBackground" scrolling="no" frameborder="0"></iframe>',
    '   <div id="textPopupWindowContent" class="textPopupcontent">',
    '       empty',
    '   </div>',
    '   <div class="dropshadow">',
    '       <div class="top">',
    '           <span class="dropshadowtopleft"></span><span class="dropshadowtopright"></span><span class="dropshadowright"></span>',
    '       </div>',
    '       <div class="bottom">',
    '           <span class="dropshadowbottomleft"></span><span class="dropshadowbottom"></span><span class="dropshadowbottomright"></span>',
    '       </div>',
    '   </div>',
    '</div>'
    );

    for(var i=0; i<textPopupHTML.length; i++) {
        document.writeln(textPopupHTML[i]);
    }

    popupWindowObj = document.getElementById('textPopupWindow');

    var browser = navigator.userAgent;
    if (browser.indexOf("MSIE") >= 0 ){
        document.getElementById("textPopupIframeBackground").style.display = 'block';
    }
}

/*
    Mouseoverhandler for showing the textPopup
*/

function showTextPopup(theObj, valign, position, size, follow, textContent) {
    /* following parameters are possible: */
    /* valign = [top|bottom|], position = [inside|outside], size = [small|medium], follow = [true|false] */
    /* textContent = [String] for dynamic content */
    
    valign = valign.toUpperCase();
    position = position.toUpperCase();
    size = size.toUpperCase();

    //check if the popup-object exists
    if(!popupWindowObj)
        return(false);

    /*
    Execute this code only at the initial mouseover of a new button object that triggers the popup,
    textpopupActive will be set to true this time and will be set to false by the reallyHide function,
    when the popup is actually hidden
    */

    if(!textPopupActive) {   //Execute only at initial mouseover
        // Set the parameters of this mouseover to global variables that can be used by other event handlers
        textPopupActiveValign = valign;
        textPopupActivePosition = position;
        textPopupActiveSize = size;
        textPopupActiveFollow = follow;

        //Changes classname of the popupwindow according to the 'valign' and 'size' parameter
        //Check alignment
        if(valign == 'TOP') {
            popupWindowObj.className = 'textPopupTop';
        }
        else if(valign == 'BOTTOM') {
            popupWindowObj.className = 'textPopupBottom';
        }
        else  {
            popupWindowObj.className = 'textPopup';
        }

        //Check size
        if(size == 'SMALL') {
            popupWindowObj.className += ' textPopupSizeSmall';
        }
        else if(size == 'MEDIUM') {
            popupWindowObj.className += ' textPopupSizeMedium';
        }
        else {
            popupWindowObj.className += ' textPopupSizeMedium';
        }

        //Look for the HTML-content of the popup and copy that into the popupwindow
        if(textContent) {
           document.getElementById('textPopupWindowContent').innerHTML = textContent;
        }

        else {
            var goNext = true;
            var sibling = theObj.nextSibling;

            //First Look for child div with classname 'popupContent'
            for(var i=0; i < theObj.childNodes.length; i++) {

                if(theObj.childNodes[i].className) {
                    if(theObj.childNodes[i].className.indexOf('popupContent') != -1) {
                        document.getElementById('textPopupWindowContent').innerHTML = theObj.childNodes[i].innerHTML;
                        goNext = false;
                    }
                }
            }

            //If that fails:
            //Look for sibling div with classname 'popupContent'

            while(goNext && sibling) {
                if(sibling.className) {
                    if(sibling.className.indexOf('popupContent') != -1) {
                        document.getElementById('textPopupWindowContent').innerHTML = sibling.innerHTML;
                        goNext = false;
                    }
                }

                if(sibling.nextSibling) {
                    sibling = sibling.nextSibling;
                }

                else {
                    goNext = false;
                }
            }
        }

        //reset the popupwindow relative to the calling object
        coords = findPosition(theObj); //find position of popup-caller button
        popupWindowObj.style.left = coords[0] + (theObj.offsetWidth/2) + "px"; //horizontally center the popup over the caller-object
        popupWindowObj.style.top = coords[1] + "px"; //basic vertical realignment

        //Further adjust the vertical coordinate according to 'valign' and 'position' property
        if(valign == 'TOP' && position == 'INSIDE') {
            //popupWindowObj.style.top = ((coords[1] - popupWindowObj.offsetHeight) + (theObj.offsetHeight/1.5)) + "px";
            popupWindowObj.style.top = ((coords[1] - popupWindowObj.offsetHeight) + (theObj.offsetHeight)/2) + "px";
        }
        else if(valign == 'BOTTOM' && position == 'INSIDE') {
            //popupWindowObj.style.top = (coords[1] + (theObj.offsetHeight*2)) + "px";
            popupWindowObj.style.top = (coords[1] + (theObj.offsetHeight*0.5)) + "px";
        }
        else if(valign == 'TOP') {
            popupWindowObj.style.top = (coords[1] - popupWindowObj.offsetHeight) + "px";
        }
        else if(valign == 'BOTTOM') {
            popupWindowObj.style.top = (coords[1] + theObj.offsetHeight) + "px";
        }

        //Find the newly defined coords of the repositioned popupwindow
        coords = findPosition(popupWindowObj);

        //Check if it is positioned outside the TOP of the screen and reposition popup at bottom align
        if((findPosition(popupWindowObj)[1] < getScrollXY()[1]) && valign == 'TOP') {   // only trigger this event when valign == TOP!
            showTextPopup(theObj, 'bottom', position, size, follow); //recursively call this function again with 'valign = bottom'
            return;
        }

        //Check if the 'follow' parameter is set to true
        if(follow) {
            if(!theObj.onmousemove)
                theObj.onmousemove = followTextPopup;  //Set the mouseover eventhandler on the caller object

            if(window.event) //only needed for IE. directly readjust popup-position to the mouse pointer
               followTextPopup(window.event);  //used in IE only for smooth transition
        }

        //Important!
        textPopupActive = true; //this popup is now active and visible
        textPopupActiveOject = theObj; //the object that called the currently activated popupwindow

        //check if there is any valid content in the popup
        if(document.getElementById('textPopupWindowContent').innerHTML.length > 2) { //Content should at least contain more than 2 characters
            //Only show if there is any content
            document.getElementById("textPopupIframeBackground").style.width = (document.getElementById("textPopupWindowContent").offsetWidth - 0) + 'px';
            document.getElementById("textPopupIframeBackground").style.height = (document.getElementById("textPopupWindowContent").offsetHeight - 0) + 'px';

            popupWindowObj.style.visibility='visible'; //Finally display the window
        }
    }

    //Cancel the hide timeout if the popupwindow receives a mouseover again from the caller OR the popupwindow itself
    else if(popupWindowObj.getAttribute("timerId") && textPopupActiveFollow == false )  {  /* if the follow option is active, then don't do this */
        clearTimeout(popupWindowObj.getAttribute("timerId"));
        popupWindowObj.setAttribute ("timerId", null);
    }

    /*
    If a mouseover is generated by another caller, then immediately hide the current popupwindow without delay and
    and recursively call the showTextPop handler with the new caller
    */

    if(textPopupActiveOject != theObj && theObj != popupWindowObj) {
        reallyHideTextPopup(); //immmediately hide the current popup
        showTextPopup(theObj, valign, position, size, follow, textContent); //call a new popup window
    }

    return;
}

/*
    Mouseout handler for delayed hiding of the popup (exeption: follow parameter = true)
*/

function hideTextPopup(theObj) {
    /*
    Try to hide submenu in case of mouseout
    Can be cancelled by a mouseover
    */

    var timerId;
    var timeOutHandler = "reallyHideTextPopup()";
    var timeOut = 500; /* standard delay (milliseconds) of mouseout */

    //check if the popup-object exists
    if(!popupWindowObj)
        return(false);

    //If the follow property of the active popup is set to true, then immediately hide
    if(textPopupActiveFollow) {
        reallyHideTextPopup();
    }
    else {
        timerId = window.setTimeout(timeOutHandler, timeOut);
        popupWindowObj.setAttribute ("timerId", timerId);
    }

    return;
}

/*
    Actually hide the popup window
*/

function reallyHideTextPopup() {
    popupWindowObj.style.visibility='hidden';  //hide the window
    clearTimeout(popupWindowObj.getAttribute("timerId"));
    popupWindowObj.setAttribute ("timerId", null); //set the timer attribute of the popupwindow to null
    textPopupActive = false; //Important! set popupwindow inactive
}

/*
    Mousemove handler in case the 'follow(mouse)' option is selected
*/

function followTextPopup(e) {

    //check if the popup-object exists
    if(!popupWindowObj)
        return(false);

    //Do not execute when there is still a timer running !!!
    if(popupWindowObj.getAttribute("timerId"))  {
        return(false);
    }

    var posx = 0;
	var posy = 0;

    if (!e) var e = window.event;

    if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}

    //adjust the horizontal position of the popupwindow
    popupWindowObj.style.left = posx + "px";

    //adjust the vertical position according to the valign property relative to mousepointer
    if(textPopupActiveValign == 'TOP') {
        popupWindowObj.style.top = posy - popupWindowObj.offsetHeight - 10 + "px";
    }
    else if(textPopupActiveValign == 'BOTTOM') {
        popupWindowObj.style.top = posy + 15 + "px";
    }

    //find the newly coords of the repositioned popupwindow
    coords = findPosition(popupWindowObj);

    //check if it is positioned outside the TOP of the screen and reposition popup at bottom align
    if(findPosition(popupWindowObj)[1] < getScrollXY()[1]) {
        reallyHideTextPopup();
        showTextPopup(textPopupActiveOject, 'bottom', textPopupActivePosition, textPopupActiveSize, true);
        return;
    }
}

/*************************************************************/
/* Functions for displaying the ressort menustrip (mainmenu) */
/*************************************************************/

var mainMenu;
var iframeBackground;
var mainMenuActive = false;

function showMainMenu() {
    if(!mainMenuActive){
        mainMenu = document.getElementById('mainMenu');
        iframeBackground = document.getElementById('mainMenuIframeBackground');

        var coords = findPosition(mainMenu);

        iframeBackground.style.left = mainMenu.style.left;
        iframeBackground.style.top = mainMenu.style.right;
        iframeBackground.style.width = mainMenu.offsetWidth + 'px';
        iframeBackground.style.height = mainMenu.offsetHeight + 'px';

        mainMenu.style.visibility = 'visible';
        iframeBackground.style.visibility = 'visible';
        mainMenuActive = true;
    }
    //Cancel the hide timeout if the popupwindow receives a mouseover again from the caller OR the popupwindow itself
    else if(mainMenu.getAttribute("timerId"))  {
        clearTimeout(mainMenu.getAttribute("timerId"));
        mainMenu.setAttribute ("timerId", null);
    }

    return;
}

function hideMainMenu() {
    /*
    Try to hide submenu in case of mouseout
    Can be cancelled by a mouseover
    */

    var timerId;
    var timeOutHandler = "reallyHideMainMenu()";
    var timeOut = 400; /* standard delay (milliseconds) of mouseout */

    timerId = window.setTimeout(timeOutHandler, timeOut);
    mainMenu.setAttribute ("timerId", timerId);

    return;
}

/*
    Actually hide the popup window
*/

function reallyHideMainMenu() {
    mainMenu.style.visibility = 'hidden';
    iframeBackground.style.visibility = 'hidden'; //hide the window

    mainMenu.setAttribute ("timerId", null); //set the timer attribute of the popupwindow to null
    mainMenuActive = false; //Important! set popupwindow inactive
    return;
}
/* ---- sortModules ---- */
/* STATUS: FINAL */

/*
*	GPR Javascript DIV sort 
*
*	Functions for sorting li layers, containing module names, on a page and saving there positions in a Cookie on every move
*
*	This script is used in the personalisation page in access manager 
*
*	USAGE 
*	
*	Create LI items containing a DIV wich contains a checkbox, the module typename and up and down arrows.
*	Thease LI items will ba sortable by the user and checkable to determain how and if the modules should 
*	be displayed on the site.
*
*		<li id="picture_gallery_teaser"><div> ... </div></li>
*	
*	Each DIV sould have two arrows with the CLASS arrowUp and arrowDown.  thease link should be children of the DIV
*
*		<a class="arrowUp" onclick="moveDivUp(this.parentNode.parentNode)"> Up arrow </a>
*		<a class="arrowDown" onclick="moveDivDown(this.parentNode.parentNode)"> Down arrow </a>
*	
*	On load read the sorted list from a Cookie and parse the container DIV in which all LI's that need sorting are available
*
*		readListFromCookie(document.getElementById('Containing_DIV'));
*
*	<ul id="moduleList">
*		<li id="picture_gallery_teaser">
*			<div class="clearfix" style="border: 1px solid #ff0000;">
*				<div style="border: 1px solid #00ff00; float: left;"><input name="chooseModuleGroup" id="picture_gallery_teaser_checkbox" type="checkbox"/>Picture gallery teaser</div>
*				<div style="border: 1px solid #ff00ff; float: right;" class="arrowContainer">
*					Sortieren<a name="arrowUp" class="arrowUp" onclick="moveDivUp(getElementById('picture_gallery_teaser'))"> Up </a>
*					<a name="arrowDown" class="arrowDown" onclick="moveDivDown(getElementById('picture_gallery_teaser'))"> Down </a>
*			</div></div></li>		
*
*
*
*	Structure
*
*		Containing_DIV 
*			LI name="type1"
*				moduleType_DIV
*					checkbox
*					module name
*					arrowUp - arrowDown
*
*			LI name="type2"
*				moduleType_DIV
*					checkbox
*					module name
*					arrowUp - arrowDown
*
*			LI name="type3"
*				moduleType_DIV
*					checkbox
*					module name
*					arrowUp - arrowDown
*
*/

function updateList(){
	removeTextNodesFromDiv(document.getElementById('moduleList'));
	showUpAndDownArrow(document.getElementById('moduleList'));
	hideFirstAndLastArrow(document.getElementById('moduleList'));
}

function moveDivUp(currentDivObject){
	divsContainer = currentDivObject.parentNode
	for (i=0; i <= divsContainer.childNodes.length-1; i++){
		if(divsContainer.childNodes[i].id == currentDivObject.id){
			// IE loses the check status when the div is moved in the tree
			var checkedBox1 = false;
			var checkedBox2 = false;

			var checkBoxObject1 = document.getElementById(divsContainer.childNodes[i].id + "_checkbox");
			var checkBoxObject2 = document.getElementById(divsContainer.childNodes[i-1].id + "_checkbox");

			// if the checkbox of this list item is checked
			if(checkBoxObject1.checked){
				checkedBox1 = true;
			}
			if(checkBoxObject2.checked){
				checkedBox2 = true;
			}
			
			// switch the LI items
			divsContainer.insertBefore(divsContainer.childNodes[i], divsContainer.childNodes[i-1]);
			
			checkBoxObject2.checked = checkedBox2;
			checkBoxObject1.checked = checkedBox1;
			
			updateList();
			break;
		}
	}
}

function moveDivDown(currentDivObject){
	divsContainer = currentDivObject.parentNode
	for (i=0; i < divsContainer.childNodes.length; i++){
		if(divsContainer.childNodes[i].id == currentDivObject.id){
			// IE loses the check status when the div is moved in the tree
			var checkedBox1 = false;
			var checkedBox2 = false;
			
			var checkBoxObject1 = document.getElementById(divsContainer.childNodes[i].id + "_checkbox");
			var checkBoxObject2 = document.getElementById(divsContainer.childNodes[i+1].id + "_checkbox");
			
			// if the checkbox of this list item is checked
			if(checkBoxObject1.checked){
				checkedBox1 = true;
			}
			if(checkBoxObject2.checked){
				checkedBox2 = true;
			}
			
			// switch the LI items
			divsContainer.insertBefore(divsContainer.childNodes[i+1], divsContainer.childNodes[i]);
			
			checkBoxObject2.checked = checkedBox2;
			checkBoxObject1.checked = checkedBox1;
			
			updateList();
			break;
		}
	}
}

function removeTextNodesFromDiv(divModulesContainer){
	var section_prio1_container = divModulesContainer;
	// remove text nodes between modules
	for (k=0; k < section_prio1_container.childNodes.length; k++){
		if(section_prio1_container.childNodes[k].nodeName == "#text"){
			section_prio1_container.removeChild(section_prio1_container.childNodes[k]);
		}
	}
}


function writeListToCookie(divModulesContainer){
	//
	// Depricated cookies for sorting the modules are now set using a paresonalisationpage in the access manager
	//
	alert("writing list to cookie");
	var section_prio1_container = divModulesContainer;
	var galleryList = new Array();
	var divCounter = 0;
	for (i=0; i < section_prio1_container.childNodes.length; i++){
		if(section_prio1_container.childNodes[i].nodeName != null  && section_prio1_container.childNodes[i].nodeName == "LI"){
			galleryList[divCounter] = new Array();
			galleryList[divCounter][0] = section_prio1_container.childNodes[i].id;
			
			//alert(document.getElementById(section_prio1_container.childNodes[i].id + "_checkbox").checked);
			galleryList[divCounter][1] = document.getElementById(section_prio1_container.childNodes[i].id + "_checkbox").checked;
			divCounter++;
		}
	}
	createCookie("sortedGalleryList",galleryList,1000);
}

function readListFromCookie(divModulesContainer){
	updateList();

	var section_prio1_container = divModulesContainer;
	if(readCookie("sortedGalleryList") != null){
		var galleryList = readCookie("sortedGalleryList").substring(1,readCookie("sortedGalleryList").length-1).split(',');

		// for every EVEN item in the galleryList get the node and append it to the container to sort the itmes
		for (i=0; i < galleryList.length; i+=2){
			for (j=0; j < section_prio1_container.childNodes.length; j++){
				if(galleryList[i] == section_prio1_container.childNodes[j].id){
					section_prio1_container.appendChild(section_prio1_container.childNodes[j]);
				}
			}
		}
		
		// for every ODD item in the galleryList get the checked state
		for (i=1; i < galleryList.length; i+=2){
			for (j=0; j < section_prio1_container.childNodes.length; j++){
				if(galleryList[i-1] == section_prio1_container.childNodes[j].id){
					if(galleryList[i] == "true"){
						document.getElementById(galleryList[i-1] + "_checkbox").checked = true;
					}else{
						document.getElementById(galleryList[i-1] + "_checkbox").checked = false;
					}
				}
			}
		}
	}
	
	for (i=0; i < section_prio1_container.childNodes.length; i++){
		if(section_prio1_container.childNodes[i] != null  && section_prio1_container.childNodes[i].nodeName == "DIV"){
			section_prio1_container.childNodes[i].style.display = 'inline';
		}
	}
	updateList();
}

function hideFirstAndLastArrow(divModulesContainer){
	removeTextNodesFromDiv(divModulesContainer);
	
	var listItems = divModulesContainer.childNodes
	
	var firstArrows = listItems[0].getElementsByTagName('A');
	var lastArrows = listItems[listItems.length-1].getElementsByTagName('A');
	
	for (i=0; i < firstArrows.length; i++){
		if(firstArrows[i].name == 'arrowUp'){
			firstArrows[i].style.display = 'none';
		}
	}
	
	for (i=0; i < lastArrows.length; i++){
		if(lastArrows[i].name == 'arrowDown'){
			lastArrows[i].style.display = 'none';
		}
	}
}

function showUpAndDownArrow(divModulesContainer){
	var upArrows = document.getElementsByName('arrowUp');
	var downArrows = document.getElementsByName('arrowDown');
	
	for(i=0; i < upArrows.length; i++){
		upArrows[i].style.display = 'inline';
	}
	
	for(i=0; i < downArrows.length; i++){
		downArrows[i].style.display = 'inline';
	}
}

/*
*	Sort modules on page function
*		
*	This function is used for displaying sorted modules on the webpage. It works by copying modules in the order stored in 
*	a cookie to a temporary div and when done copying the inner html from this Div over the modulebar content.
*
*	usage:
*		
*		sortModulesOnPage(divModulesContainer,debugModuleList)
*
*		divModulesContainer		- Should contain the name of the rightColumn
*		divTempModuleContainer	- The name of the hidden div in the page to copy the modules to		
*
*	debug version
*		
*		sortModulesOnPage(divModulesContainer,divTempModuleContainer,debugModuleList,divMainColumn)
*
*		divModulesContainer		- Should contain the name of the rightColumn
*		divTempModuleContainer	- The name of the hidden div in the page to copy the modules to	
*		debugModuleList			- Default false, when true it displays debug information for this function		
*		divMainColumn			- The name of the output div for debugging information
*
*	requires: the following divs
*			
*		rightColumn 			- This is the div with the modules
*		tempModuleDiv			- A hidden div to copy the modules to
*		mainColumn	(1)			- The main div of the page to copy the debug information to	
*		
*		(1) optional 
*/

// Default version
function sortModulesOnPage(divModulesContainer,divTempModuleContainer){
	sortModulesOnPage(divModulesContainer,divTempModuleContainer,false,null);
}

// Default version and Debug version
function sortModulesOnPage(divModulesContainer,divTempModuleContainer,debugModuleList,divMainColumn){
	var rightModuleContainer = document.getElementById(divModulesContainer);
	var tempModuleContainer = document.getElementById(divTempModuleContainer);
	var mainColumn = document.getElementById(divMainColumn);
	
	if(readCookie("sortedGalleryList") != null){
		var sortLog = readCookie("sortedGalleryList");
	
		var galleryList = readCookie("sortedGalleryList").substring(1,readCookie("sortedGalleryList").length-1).split(',');

		
		
		// remove comments and tekstnodes
		for (j=0; j < rightModuleContainer.childNodes.length; j++){
			if(rightModuleContainer.childNodes[j].nodeName != "DIV"){
				try{
					rightModuleContainer.removeChild(rightModuleContainer.childNodes[j]);
				}catch(err){}
			}
		}

		sortLog += "<h2>Hide and make visible</h2><br>"
		
		// for every ODD item in the galleryList get the checked state
		for (i=1; i < galleryList.length; i+=2){
			for (j=0; j < rightModuleContainer.childNodes.length; j++){
				if(rightModuleContainer.childNodes[j].nodeName == "DIV"){
					moduleType = rightModuleContainer.childNodes[j].id.split('_sep_');
					if(galleryList[i-1] == moduleType[1]){
						if(galleryList[i] == "true"){
							sortLog += rightModuleContainer.childNodes[j].id + " to visible<br>"
							rightModuleContainer.childNodes[j].style.display = "block";
						}else{
							sortLog += rightModuleContainer.childNodes[j].id + " to hidden<br>"
							rightModuleContainer.childNodes[j].style.display = "none";
						}
					}
				}
			}
		}
		sortLog += "<br><h2>Sort modules according to cookie</h2>"

		// for every EVEN item in the galleryList get the node and append it to the container to sort the itmes
		var bannerPositionCounter = 0;
		for (i=0; i < galleryList.length; i+=2){
			sortLog += "<br>Check " + galleryList[i] + "<br>";
			try{
				for (j=0; j < rightModuleContainer.childNodes.length; j++){
					if(rightModuleContainer.childNodes[j].nodeName == "DIV"){
						moduleType = rightModuleContainer.childNodes[j].id.split('_sep_');
						sortLog += "Check " + galleryList[i] + " == " + moduleType[1] + "<br>"
						if(galleryList[i] == moduleType[1]){
							sortLog += "Moving " + rightModuleContainer.childNodes[j].id + "<br>";
							
							// add the first banner 
							// Node needs to be cloned becouse otherwhise the sorting ot the elements will fail because the amount of objects won't be correct.
							
							// put the banner above the right site column for sorting in IE
							if(bannerPositionCounter == 0){
								// alert('printing banner');
								bannerPositionCounter++;
								if(document.getElementById('banner_1')){
									//tempModuleContainer.appendChild(document.getElementById('banner_1').cloneNode(true));
								}	
								
								/*
								if(typeof(adlink_randomnumber)=="undefined") var adlink_randomnumber=Math.floor(Math.random()*1000000000000);
								//var bannerTag = document.write('<'+'script type="text/javascript" src="http://ad.de.doubleclick.net/adj/Welt/home;tile=2;sz=120x600;ord=' + adlink_randomnumber + '?"><'+'/script>');

								var myElement = document.createElement('script'); 
								//myElement.innerHTML = 'http://ad.de.doubleclick.net/adj/Welt/home;tile=2;sz=120x600;ord=' + adlink_randomnumber + '?';

								
								myElement.src = 'http://ad.de.doubleclick.net/adj/Welt/home;tile=2;sz=120x600;ord=' + adlink_randomnumber + '?';
								
								
								tempModuleContainer.appendChild(myElement);
								
								
								myElement.innerHTML = 'http://ad.de.doubleclick.net/adj/Welt/home;tile=2;sz=120x600;ord=' + adlink_randomnumber + '?';
								tempModuleContainer.appendChild(myElement);
								*/
								
							}
							
							
							var	textNode = rightModuleContainer.childNodes[j].cloneNode(true);
							tempModuleContainer.appendChild(textNode);
							
							
							if(rightModuleContainer.childNodes[j]){
								if(rightModuleContainer.childNodes[j].style.display == "block"){
									bannerPositionCounter++;
								}
							}
							
							// add the second banner (Not needed becouse currently only the homepage will be personalised)
							// Node needs to be cloned becouse otherwhise the sorting ot the elements will fail because the amount of objects won't be correct.
							/*
							if(bannerPositionCounter == 2){
								if(document.getElementById('banner_2')){							
									tempModuleContainer.appendChild(document.getElementById('banner_2').cloneNode(true));
								}
							}
							*/
						}
					}
				}
			}catch(err){
				alert("error checking Div: " + err.description);
			}
		}
		
		// Print the remaining modules if they haven't been printed in between the modules, 
		// this might accure when there are only a few modules desked or selected in the personalisation.
		
		// add the second banner (Not needed becouse currently only the homepage will be personalised)
		/*
		if(bannerPositionCounter < 2){
			if(document.getElementById('banner_2')){	
				tempModuleContainer.appendChild(document.getElementById('banner_2'));
			}
		}
		*/

		if(divMainColumn != null && debugModuleList == true){
			mainColumn.innerHTML = "<h1>Javascript module sort debug</h1><br>" + sortLog;
		}
		rightModuleContainer.innerHTML = tempModuleContainer.innerHTML

		// Clear the data in the temp madule container 
		tempModuleContainer.innerHTML = "";		
	}
}


// This is where the flash objects are executed. This function needs to be called after the sorting routine, 
// because executing thease objects before sorting will result in  blank flash objects in IE.
function executePodcastObjectsInModules(podcastList){
	// More then one podcast article can be desked so this loop executes all the corresponing articles
	for(i=0;i < podcastList.length;i++){
		var mp3Player = eval('mp3Player_'+ podcastList[i]);
		mp3Player.addParam("allowScriptAccess", "sameDomain");
		mp3Player.addParam("menu", "false");
		mp3Player.addParam("quality", "high");
		mp3Player.addParam("align", "middle");
		mp3Player.addParam("wmode", "opaque");
		mp3Player.addVariable("beginPlaying", false);
		mp3Player.addVariable("mp3Path", eval('mp3PlayerMediaURL_'+ podcastList[i]));
		mp3Player.write('flashMp3Player_' + podcastList[i]);
	}
}

// This is where the flash objects are executed. This function needs to be called after the sorting routine, 
// because executing thease objects before sorting will result in  blank flash objects in IE.	
function executeVideoObjectInModules(so){
	// there can only be one video module for the time being. 
	so.addParam( "allowScriptAccess", "sameDomain" );
	so.addParam( "menu", "false" );
	so.addParam( "quality", "high" );
	so.addParam( "id", "mediaplayer" );
	so.addParam( "align", "middle" );
	so.addParam( "wmode", "opaque" );

    so.addVariable( "autoPlay", "true" );
    so.addVariable( "startClip", "0" );
    so.addVariable( "libraryPath", soLibraryPath );
	so.addVariable( "defaultMediaAssetPath", soDefaultMediaAssetPath );
	so.addVariable( "bwCheckUrl", soBwCheckUrl );
	so.addVariable( "eaeLoggerPath", soEaeLoggerPath );
	so.addVariable( "eaeLoggerPubId", soEaeLoggerPubId );
	so.addVariable( "eaeLoggerType", "video" );
	so.addVariable( "mediacliplist", soMediacliplist);
	so.addVariable( "ivwStatsFunction", "ivwLogVideo" );
	//so.write( "teaservideo" );
}
/* ---- print ---- */
/* STATUS:CHECKED Todo: should this file be integrated in a global js? */

var display_img_print = false;
function switchDisplayImages()
{
	//go through the domtree of article and set display to none
	divs = document.getElementById("article").getElementsByTagName("div");
	for (i=0; i<divs.length; i++)
	{
		switch (divs[i].className)
		{
			case "imageHeadline":
			case "imageLeft":
			case "imageCenter":
			case "imageRight":
			case "inlineGallery":
                divs[i].style.display = (display_img_print ? "block" : "none");

			default: break;
		}
	}
	display_img_print = !display_img_print;
}

function printArticle()
{
	window.print();
}
/* ---- search ---- */
//TODO: define German alerts
//method cleanSearchExpression: cleans expression in expressoin fields after an search with calendar
//method searchSubmitAdvanced: validates expression for submit. see also search-advanced.jsp
//method searchSubmitTop: validates expression for submit. see also search-simpel.jsp
//method searchSubmitInternal: validates expression for submit . see also search-simple-result.jsp
//method TrimString: does a String.Trim()

//cleanin inputbox from search-expression of calendar
function cleanSearchExpression(){
  try{
  //clean top inputbox
  var formTop = document['searchFormTop'];
  if (formTop==null){

  } else{
     var expression = formTop["lucyExpr"].value;
     expression = TrimString(expression);
      if ((expression=='ei*')||(expression=='de*')){
       formTop["lucyExpr"].value='';
    }
  }
  //clean advanced search inputbox
  var formAdvanced=document['searchForm'];
  if (formAdvanced==null){

  } else{
     var expression = formAdvanced["lucyExpr"].value;
     expression = TrimString(expression);
      if ((expression=='ei*')||(expression=='de*')){
       formAdvanced["lucyExpr"].value='';
    }
  }
  
  var formAdvancedInternal = document['searchFormInternal'];
  if (formAdvancedInternal==null){

  } else{
     var expression = formAdvancedInternal["lucyExpr"].value;
     expression = TrimString(expression);
      if ((expression=='ei*')||(expression=='de*')){
       formAdvancedInternal["lucyExpr"].value='';
    }
  }
    }catch (E){

  }
}
function TrimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}
 //validating  document['searchForm']['lucyExpr']
function searchSubmitAdvanced(searchForm){
   try{
  var expression = searchForm["lucyExpr"].value;
   expression = TrimString(expression);
  
  var valid = true;
   if (expression.length<3){
     valid = false;
   }

  if ((expression.charAt(0)=='*')||(expression.charAt(0)=='?')){
    valid = false;
  }

  if ((expression=='ei*')||(expression=='de*')){
    valid = false;
  }
  if (valid){
    searchForm.submit()
    }else{
    alert('Bitte geben sie einen Suchbegriff ein.')
  }
     }catch (E){

   }
  return valid;
}
 //validating  document['searchFormTop']['lucyExpr']
function searchSubmitSimple(searchForm){
  //alert(searchForm);
   try{
   var expression = searchForm["lucyExpr"].value;
   expression = TrimString(expression);

  var valid = true;
   if (expression.length<3){
     valid = false;
   }

  if ((expression.charAt(0)=='*')||(expression.charAt(0)=='?')){
    valid = false;
  }
  if ((expression=='ei*')||(expression=='de*')){
    valid = false;
  }
  if (valid){
    searchForm.submit()
    }else{
    alert('Bitte geben sie einen Suchbegriff ein.')
  }
     }catch (E){

   }
  return valid;
}
//validating  document['searchFormInternal']['lucyExpr']
function searchSubmitSimpleInternal(searchForm){
  //alert(searchForm);
  try{
   var expression = searchForm["lucyExpr"].value;
   expression = TrimString(expression);

  var valid = true;
   if (expression.length<3){
     valid = false;
   }

  if ((expression.charAt(0)=='*')||(expression.charAt(0)=='?')){
    valid = false;
  }
 if ((expression=='ei*')||(expression=='de*')){
    valid = false;
  }
  if (valid){
    searchForm.submit()
    }else{
    alert('Bitte geben sie einen Suchbegriff ein.')
  }
    }catch (E){
    
  }
  return valid;
}
/* ---- mp3Player ---- */
function startMp3Player(mp3FilePath,divName,startPlaying){
	mp3Player.addParam("allowScriptAccess", "sameDomain");
	mp3Player.addParam("menu", "false");
	mp3Player.addParam("quality", "high");
	mp3Player.addParam("align", "middle");
	mp3Player.addParam("wmode", "opaque");
	mp3Player.addVariable("beginPlaying", startPlaying);
	mp3Player.addVariable("mp3Path", mp3FilePath);
	mp3Player.write(divName);
}
function ivwLogMp3Player(){
	getCounters();
}
/* ---- video ---- */

function showMainPlayerDefer( mediaclip, player ) {
	var popupUrl = mediaclip;
	if ( mediaclip.indexOf( "?" ) > -1 ) {
		popupUrl = mediaclip.substr( 0, mediaclip.indexOf( "?" ) );
	}
	popupUrl += "?service=VideoPopup";
	var videowindow;
	if ( player == "adv" ) {
		popupUrl += "&player=adv";
		videowindow = window.open( popupUrl, "video", "width=492,height=433,location=0,menubar=0,resizable=0,scrollbars=0,toolbar=0,status=0" );
	}
	else {
		videowindow = window.open( popupUrl, "video", "width=748,height=433,location=0,menubar=0,resizable=0,scrollbars=0,toolbar=0,status=0" );
	}
	if ( videowindow.opener ) videowindow.opener = self;
	videowindow.focus();
}


function showMainPlayer( mediaclip, player ) {
	setTimeout( "showMainPlayerDefer( '" + mediaclip + "', '" + player + "' )", 100 );
}


function showMoreVideos() {
	if ( window.opener ) {
		window.opener.location = "/videos/";
		window.opener.focus();
		window.close();
	}
	else {
		window.open( "/videos/" );
		window.close();
	}
}


function ivwLogVideo( parameters ) {
	var ivw = "<img src=\"http://welt.ivwbox.de/cgi-bin/ivw/CP/videoteaser?r=" + escape(document.referrer) + "&d=" + (Math.random()*100000) + "\" width=\"1\" height=\"1\" alt=\"\" class=\"countPixel\"/>";

	videoUrl = parameters.url;
	if ( videoUrl.indexOf( "?" ) >= 0 ) videoUrl = videoUrl.substr( 0, videoUrl.indexOf( "?" ) );
	if ( videoUrl.substr( 0, 7 ) == "http://" ) {
		videoUrl = videoUrl.substr( 7 );
		videoUrl = videoUrl.substr( videoUrl.indexOf( "/" ) );
	}
	ivw += "<img src=\"http://ivw.ullstein-online.de/ivw/CP/welt" + escape(videoUrl) + "/_x_?d=" + (Math.random()*100000) + "\" width=\"1\" height=\"1\" alt=\"\" class=\"countPixel\" id=\"localCountPixel\"/>";

	var ivwElement = document.getElementById( "ivw" );
	if ( ivwElement ) {
		ivwElement.innerHTML = ivw;
	}


	if (typeof s == 'object'){
		s.pageName = "Video "+parameters.id+": "+parameters.title;
		s.prop5 = "Video";
		s.prop7 = parameters.bandwidth;
		s.prop3 = parameters.id;

		var code = s.t();
		if (code){
			document.getElementById("siteCatalystSink").innerHTML = code;
		}
	}

}


/* ---- loadDataToCookies ---- */
var xmlhttp	

function loadXMLDoc(url)
{
	xmlhttp=null
	// code for Mozilla, etc.
	if (window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest()
	}
	// code for IE
	else if (window.ActiveXObject){
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	}if (xmlhttp!=null){
		xmlhttp.onreadystatechange=state_Change
		xmlhttp.open("GET",url,true)
		xmlhttp.send(null)
	}else{
		alert("Your browser does not support XMLHTTP.")
	}
}

function state_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
	{
	  // if "OK"
		if (xmlhttp.status==200)
		{
			// xmlhttp.status
			// xmlhttp.statusText
			// xmlhttp.responseText
			try{
				loadDataToCookies(xmlhttp.responseText);
			}
			catch(err){
			}
		}
		else
		{
		}
	}
}

function loadDataToCookies(text){

	// this script is used to make shure that the profile information is directly available as cookie information 
	// without having to do a login.	
	
	// Create a DOM tree from the personalisation information in http://*.welt.de/?service=Login
	
	
	// convert string to an XML doc
	
	// code for IE
	if (window.ActiveXObject)
	{
		var doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(text);
	}
	// code for Mozilla, Firefox, Opera, etc.
	else
	{
		var parser=new DOMParser();
		var doc=parser.parseFromString(text,"text/xml");
	}
	
	// Loop trough the DOM tree to find the information for the cookie
	var root = doc.documentElement;
	 for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
		var node = root.childNodes.item(iNode);
		
		// remove #text nodes in firefox
		if (!window.ActiveXObject)
		{
			for (i = 0; i < node.childNodes.length; i++) {
				if(node.childNodes.item(i).nodeName == "#text"){
					node.removeChild(node.childNodes.item(i));
				}
			}
		}
		
		// loop trough all nodes to find RSSfeeds and sorted gallery list
		for (i = 0; i < node.childNodes.length; i++) {
			//debugString += " " + node.childNodes.item(i).nodeName + "\n";
			try{
				//debugString += " " + node.childNodes.item(i).childNodes[0].nodeValue + "\n";
				if(node.childNodes.item(i).childNodes[0].nodeValue == "RSSfeeds"){
				
					// quotes are there becouse access manager also puts quotes around its session cookie values
					createCookie("RSSfeeds","\"" + node.childNodes.item(i-1).childNodes[0].nodeValue + "\"",365);	
				}
				if(node.childNodes.item(i).childNodes[0].nodeValue == "sortedGalleryList"){

					// quotes are there becouse access manager also puts quotes around its session cookie values
					createCookie("sortedGalleryList","\"" + node.childNodes.item(i-1).childNodes[0].nodeValue + "\"",365);
					
					var browser = navigator.userAgent;
					if ( browser.indexOf("Safari")>=0 || browser.indexOf("Konqueror")>=0 ){
						eraseCookie("sortedGalleryList");
					}
				}
			}catch(err){
			}
		}
	}
}

function logoutButton(){
	if(readCookie('userId') != null)
	{	//document.getElementById('LoginRegister').innerHTML = "<a class=\"arrowLink\" href=\"/action?action=logout\">Abmelden</a>";
		document.getElementById('LoginRegister').innerHTML = "<a href=\"/action?action=logout\">Abmelden</a>";
	}
}
		

if(readCookie("userId") != null){
	loadXMLDoc('/?service=Login');
}else{
	if(readCookie("RSSfeeds") != null){
		eraseCookie("RSSfeeds");
	}
	if(readCookie("sortedGalleryList") != null){
		eraseCookie("sortedGalleryList");
	}
}
/* ---- gallery ---- */
/* STATUS:FINAL */

/*
	This function can be used in two ways.
	Using the a href object.
	or
	Using the image id.
*/

function openImageGalleryPopup(Url) {
    window.open(Url,'picture_gallery','menubar=no, toolbar=no, status=no, width=665, height=565, scrollbars=no, resizable=no');
}

var waitingTimeoutId = null;

function viewImage(linkElement, number) {
	if (number != null) imageId = number;
	else imageId = linkElement.name;
	curr = images[imageId];
		
	imgNode = document.getElementById("fullimage");

    document.getElementById('hourglass').style.visibility = 'hidden';   /* hide hourglass if still visible */
    //Hide & Clear the old image, then change the properties and..
	imgNode.style.visibility = 'hidden';
    imgNode.src = "";
	imgNode.src = curr[0];

    //imgNode.width = (curr[6] > 305 ? (305*curr[5]) / curr[6] : curr[5]);
	//imgNode.height = (curr[6] > 305 ? 305 : curr[6]);
	imgNode.width = curr[5];
	imgNode.height = curr[6];
    imgNode.alt = imgNode.title = curr[4];

	// document.getElementById("fullimage_author").innerHTML = curr[11];
	document.getElementById("fullimage_copy").innerHTML = curr[3];
	// document.getElementById("fullimage_headline").innerHTML = curr[1];
	document.getElementById("fullimage_intro").innerHTML = curr[2];
	document.getElementById("fullimage_index").innerHTML = curr[8];
	document.getElementById("fullimage_back").name= curr[9];
	document.getElementById("fullimage_forward").name = curr[10];
    document.getElementById("fullimage_forward_imagebutton").name = curr[10];
    
    //..then show the new image
	//imgNode.style.visibility = 'visible';
	// DM: moved above instruction to the onload function of the image itself ;)
    //document.getElementById("fullimage").style.marginTop = "" + (305 - curr[6] > 0 ? (305 - curr[6])/2 : 0) + "px";
    waitingTimeoutId = window.setTimeout("document.getElementById('hourglass').style.visibility = 'visible';",900);
}

function drawPicturebar(linkElement,picturebarLength,picturebarPageLength) {
	
	var parent = document.getElementById("filmstrip");
	var nodes = parent.childNodes;
	var from = linkElement.name * picturebarLength;
	
	var curpage = from/picturebarLength;
	
	var backnr = curpage-1;
	var forwnr = curpage+1;
	
	if ( backnr<0 ) { backnr = picturebarPageLength; }
	
	if ( forwnr>picturebarPageLength ) { forwnr = 0; }
	
	for (var i = 0; i < nodes.length; i++) {
		node = nodes[i];
		if (node.className == "pictures") {
			// First remove all the child nodes;
			while (node.childNodes[0]) node.removeChild(node.childNodes[0]);
			for (var j=from; j < images.length && j < (from+picturebarLength); j++) {

				var ahref = document.createElement('a');
				ahref.name = j;
				ahref.href = "#";
		
				var div = document.createElement('div');
				div.className = "picture";

				if (window.attachEvent) {
					ahref.href = "javascript: viewImage('', "+j+");";
				} else {
					ahref.setAttribute("onClick", "viewImage(this);");
				}
					
				var img = document.createElement('img');
				img.src = images[j][12];
				img.height = images[j][14] > 43 ? 43 : images[j][14];
				img.alt = images[j][4];
				img.title = images[j][4];
				
				ahref.appendChild(img);
				div.appendChild(ahref);
				node.appendChild(div);
			}
		}
	}
	document.getElementById("galBack").name=backnr;
	document.getElementById("galForward").name=forwnr;
}


function reloadAdFrame () {
  var adlink_randomnumber=Math.floor(Math.random()*1000000000000);

  // Definition der "Grundhoehen und Breiten der Werbemittel:
  var adProp = new Array();
  adProp['Head'] = new Object();
  adProp['Head']['style'] = "width: 738px; height: 90px";  // 728x90
  adProp['Head']['id'] = "bannerHead";
  adProp['Skyscraper'] = new Object();
  adProp['Skyscraper']['style'] = "width: 160px; height; 600px";  // 120x600
  adProp['Skyscraper']['id'] = "bannerSkyscraper";
  adProp['Rectangle'] = new Object();
  adProp['Rectangle']['style'] = "width: 320px; height: 255px";  // 300x250
  adProp['Rectangle']['id'] = "banner_1";

  // Um ein Neuladen zu erzwingen, haengen wir die Bildnummer in die URL:
  var url = document.location.href;
  var imageNr = 0;
  document.getElementById && document.getElementById('fullimage_index') && (imageNr = document.getElementById('fullimage_index').innerHTML);
  url = url.replace(/\.html/,'_'+imageNr+'.html');


  for (var ad in adProp){

    // Wir maskieren die AD-Position als Satische URL
    // Eine Apache-Rewrite setzt dem Tomcat dann wieder ein ?service=Adframe&Position=ad vor:
    var urlFrame = url + '/AdFrame_' + ad + '.html';

    // Beim ersten Bild hat die Seite keine AD-Frames, sondern direkt eingebaute AD-Codes.
    // Wir suchen den Container ueber die ID und und plazieren dann einen IFrame. Bei den
    // reslichen Bildern gibt es schon einen IFrame - wir aendern dann das Attributr "src":

    var adContainer;
    if (document.getElementById && (adContainer = document.getElementById(adProp[ad]['id']))) {
      if (adContainer.firstChild && adContainer.firstChild.nodeName == 'IFRAME'){
        adContainer.firstChild.src = urlFrame;
      } else {
        adContainer.innerHTML = '<iframe style="' + adProp[ad]['style'] + '" src="' + urlFrame + '" scrolling="no" frameborder="0"></iframe>';
      }
    }
  }
}
/* ---- swfobject ---- */
/* STATUS:FINAL */

/**
 * SWFObject v1.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
try
{ 

if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}

deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b)
{
	if(!document.createElement||!document.getElementById){return;}
	
	this.DETECT_KEY=_b?_b:"detectflash";
	this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
	this.params=new Object();
	this.variables=new Object();
	this.attributes=new Array();
	
	if(_1){this.setAttribute("swf",_1);}
	if(id){this.setAttribute("id",id);}
	if(w){this.setAttribute("width",w);}
	if(h){this.setAttribute("height",h);}
	if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}

	this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute("version"),_7);
	if(c){this.addParam("bgcolor",c);}
	
	var q=_8?_8:"high";
	this.addParam("quality",q);
	this.setAttribute("useExpressInstall",_7);
	this.setAttribute("doExpressInstall",false);
	var _d=(_9)?_9:window.location;
	
	this.setAttribute("xiRedirectUrl",_d);
	this.setAttribute("redirectUrl","");
	if(_a){this.setAttribute("redirectUrl",_a);}
};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){
_16.push(key+"="+_18[key]);}
return _16;
},getSWFHTML:function(){
var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}
_19+="/>";
}else{
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}
_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
	var n=(typeof _20=="string")?document.getElementById(_20):_20;
	if (n)
		n.innerHTML=this.getSWFHTML();
	return true;
}else{
if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(_23,_24){
var _25=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_25=new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{
var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
for(var i=3;axo!=null;i++){
axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
_25=new deconcept.PlayerVersion([i,0,0]);}}
catch(e){}
if(_23&&_25.major>_23.major){return _25;}
if(!_23||((_23.minor!=0||_23.rev!=0)&&_25.major==_23.major)||_25.major!=6||_24){
try{_25=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}
catch(e){}}}
return _25;};
deconcept.PlayerVersion=function(_29){
this.major=parseInt(_29[0])!=null?parseInt(_29[0]):0;
this.minor=parseInt(_29[1])||0;
this.rev=parseInt(_29[2])||0;};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){return false;}return true;};
deconcept.util={getRequestParameter:function(_2b){
var q=document.location.search||document.location.hash;
if(q){
var _2d=q.indexOf(_2b+"=");
var _2e=(q.indexOf("&",_2d)>-1)?q.indexOf("&",_2d):q.length;
if(q.length>1&&_2d>-1){
return q.substring(q.indexOf("=",_2d)+1,_2e);
}}return "";}};
if(Array.prototype.push==null){
Array.prototype.push=function(_2f){
this[this.length]=_2f;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject; // for backwards compatibility
var SWFObject=deconcept.SWFObject;

}
catch(e)
{	
}

/* ---- neofonie archiv ---- */
/*  Prototype JavaScript framework, version 1.5.0
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.0',
  BrowserFeatures: {
    XPath: !!document.evaluate
  },

  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  emptyFunction: function() {},
  K: function(x) { return x }
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
String.interpret = function(value){
  return value == null ? '' : String(value);
}

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};

    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var name = decodeURIComponent(pair[0]);
        var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;

        if (hash[name] !== undefined) {
          if (hash[name].constructor != Array)
            hash[name] = [hash[name]];
          if (value) hash[name].push(value);
        }
        else hash[name] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function(){
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.replace(/\\/g, '\\\\');
    if (useDoubleQuotes)
      return '"' + escapedString.replace(/"/g, '\\"') + '"';
    else
      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(object[match[3]]);
    });
  }
}

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator) {
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.map(iterator);
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push((iterator || Prototype.K)(value, index));
    });
    return results;
  },

  detect: function(iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = fillWith === undefined ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0, length = this.length; i < length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function() {
    return this.inject([], function(array, value) {
      return array.include(value) ? array : array.concat([value]);
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});

Array.prototype.toArray = Array.prototype.clone;

function $w(string){
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if(window.opera){
  Array.prototype.concat = function(){
    var array = [];
    for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for(var i = 0, length = arguments.length; i < length; i++) {
      if(arguments[i].constructor == Array) {
        for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  }
}
var Hash = function(obj) {
  Object.extend(this, obj || {});
};

Object.extend(Hash, {
  toQueryString: function(obj) {
    var parts = [];

	  this.prototype._each.call(obj, function(pair) {
      if (!pair.key) return;

      if (pair.value && pair.value.constructor == Array) {
        var values = pair.value.compact();
        if (values.length < 2) pair.value = values.reduce();
        else {
        	key = encodeURIComponent(pair.key);
          values.each(function(value) {
            value = value != undefined ? encodeURIComponent(value) : '';
            parts.push(key + '=' + encodeURIComponent(value));
          });
          return;
        }
      }
      if (pair.value == undefined) pair[1] = '';
      parts.push(pair.map(encodeURIComponent).join('='));
	  });

    return parts.join('&');
  }
});

Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (value && value == Hash.prototype[key]) continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject(this, function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  remove: function() {
    var result;
    for(var i = 0, length = arguments.length; i < length; i++) {
      var value = this[arguments[i]];
      if (value !== undefined){
        if (result === undefined) result = value;
        else {
          if (result.constructor != Array) result = [result];
          result.push(value)
        }
      }
      delete this[arguments[i]];
    }
    return result;
  },

  toQueryString: function() {
    return Hash.toQueryString(this);
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
});

function $H(object) {
  if (object && object.constructor == Hash) return object;
  return new Hash(object);
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   ''
    }
    Object.extend(this.options, options || {});

    this.options.method = this.options.method.toLowerCase();
    if (typeof this.options.parameters == 'string')
      this.options.parameters = this.options.parameters.toQueryParams();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  _complete: false,

  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = this.options.parameters;

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    params = Hash.toQueryString(params);
    if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='

    // when GET, append parameters to URL
    if (this.method == 'get' && params)
      this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;

    try {
      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      var body = this.method == 'post' ? (this.options.postBody || params) : null;

      this.transport.send(body);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    }
    catch (e) {
      this.dispatchException(e);
    }
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (typeof extras.push == 'function')
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  success: function() {
    return !this.transport.status
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.getHeader('Content-type') || 'text/javascript').strip().
        match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
          this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + state, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) { return null }
  },

  evalJSON: function() {
    try {
      var json = this.getHeader('X-JSON');
      return json ? eval('(' + json + ')') : null;
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, param) {
      this.updateContent();
      onComplete(transport, param);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.container[this.success() ? 'success' : 'failure'];
    var response = this.transport.responseText;

    if (!this.options.evalScripts) response = response.stripScripts();

    if (receiver = $(receiver)) {
      if (this.options.insertion)
        new this.options.insertion(receiver, response);
      else
        receiver.update(response);
    }

    if (this.success()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    element = document.getElementById(element);
  return Element.extend(element);
}

if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
    var results = [];
    var query = document.evaluate(expression, $(parentElement) || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
      results.push(query.snapshotItem(i));
    return results;
  };
}

document.getElementsByClassName = function(className, parentElement) {
  if (Prototype.BrowserFeatures.XPath) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return document._getElementsByXPath(q, parentElement);
  } else {
    var children = ($(parentElement) || document.body).getElementsByTagName('*');
    var elements = [], child;
    for (var i = 0, length = children.length; i < length; i++) {
      child = children[i];
      if (Element.hasClassName(child, className))
        elements.push(Element.extend(child));
    }
    return elements;
  }
};

/*--------------------------------------------------------------------------*/

if (!window.Element)
  var Element = new Object();

Element.extend = function(element) {
  if (!element || _nativeExtensions || element.nodeType == 3) return element;

  if (!element._extended && element.tagName && element != window) {
    var methods = Object.clone(Element.Methods), cache = Element.extend.cache;

    if (element.tagName == 'FORM')
      Object.extend(methods, Form.Methods);
    if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
      Object.extend(methods, Form.Element.Methods);

    Object.extend(methods, Element.Methods.Simulated);

    for (var property in methods) {
      var value = methods[property];
      if (typeof value == 'function' && !(property in element))
        element[property] = cache.findOrStore(value);
    }
  }

  element._extended = true;
  return element;
};

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
};

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, html) {
    html = typeof html == 'undefined' ? '' : html.toString();
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  replace: function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    return $A($(element).getElementsByTagName('*'));
  },

  immediateDescendants: function(element) {
    if (!(element = $(element).firstChild)) return [];
    while (element && element.nodeType != 1) element = element.nextSibling;
    if (element) return [element].concat($(element).nextSiblings());
    return [];
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    if (typeof selector == 'string')
      selector = new Selector(selector);
    return selector.match($(element));
  },

  up: function(element, expression, index) {
    return Selector.findElement($(element).ancestors(), expression, index);
  },

  down: function(element, expression, index) {
    return Selector.findElement($(element).descendants(), expression, index);
  },

  previous: function(element, expression, index) {
    return Selector.findElement($(element).previousSiblings(), expression, index);
  },

  next: function(element, expression, index) {
    return Selector.findElement($(element).nextSiblings(), expression, index);
  },

  getElementsBySelector: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  getElementsByClassName: function(element, className) {
    return document.getElementsByClassName(className, element);
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (document.all && !window.opera) {
      var t = Element._attributeTranslations;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name])  name = t.names[name];
      var attribute = element.attributes[name];
      if(attribute) return attribute.nodeValue;
    }
    return element.getAttribute(name);
  },

  getHeight: function(element) {
    return $(element).getDimensions().height;
  },

  getWidth: function(element) {
    return $(element).getDimensions().width;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    var elementClassName = element.className;
    if (elementClassName.length == 0) return false;
    if (elementClassName == className ||
        elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      return true;
    return false;
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).add(className);
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).remove(className);
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
    return element;
  },

  observe: function() {
    Event.observe.apply(Event, arguments);
    return $A(arguments).first();
  },

  stopObserving: function() {
    Event.stopObserving.apply(Event, arguments);
    return $A(arguments).first();
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  descendantOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = Position.cumulativeOffset(element);
    window.scrollTo(pos[0], pos[1]);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    if (['float','cssFloat'].include(style))
      style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
    style = style.camelize();
    var value = element.style[style];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css[style] : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style];
      }
    }

    if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
      value = element['offset'+style.capitalize()] + 'px';

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';
    if(style == 'opacity') {
      if(value) return parseFloat(value);
      if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
        if(value[1]) return parseFloat(value[1]) / 100;
      return 1.0;
    }
    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (var name in style) {
      var value = style[name];
      if(name == 'opacity') {
        if (value == 1) {
          value = (/Gecko/.test(navigator.userAgent) &&
            !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
        } else if(value === '') {
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
        } else {
          if(value < 0.00001) value = 0;
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
              'alpha(opacity='+value*100+')';
        }
      } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
      element.style[name.camelize()] = value;
    }
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return element;
    element._overflow = element.style.overflow || 'auto';
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return element;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  }
};

Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});

Element._attributeTranslations = {};

Element._attributeTranslations.names = {
  colspan:   "colSpan",
  rowspan:   "rowSpan",
  valign:    "vAlign",
  datetime:  "dateTime",
  accesskey: "accessKey",
  tabindex:  "tabIndex",
  enctype:   "encType",
  maxlength: "maxLength",
  readonly:  "readOnly",
  longdesc:  "longDesc"
};

Element._attributeTranslations.values = {
  _getAttr: function(element, attribute) {
    return element.getAttribute(attribute, 2);
  },

  _flag: function(element, attribute) {
    return $(element).hasAttribute(attribute) ? attribute : null;
  },

  style: function(element) {
    return element.style.cssText.toLowerCase();
  },

  title: function(element) {
    var node = element.getAttributeNode('title');
    return node.specified ? node.nodeValue : null;
  }
};

Object.extend(Element._attributeTranslations.values, {
  href: Element._attributeTranslations.values._getAttr,
  src:  Element._attributeTranslations.values._getAttr,
  disabled: Element._attributeTranslations.values._flag,
  checked:  Element._attributeTranslations.values._flag,
  readonly: Element._attributeTranslations.values._flag,
  multiple: Element._attributeTranslations.values._flag
});

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    var t = Element._attributeTranslations;
    attribute = t.names[attribute] || attribute;
    return $(element).getAttributeNode(attribute).specified;
  }
};

// IE is missing .innerHTML support for TABLE-related elements
if (document.all && !window.opera){
  Element.Methods.update = function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    var tagName = element.tagName.toUpperCase();
    if (['THEAD','TBODY','TR','TD'].include(tagName)) {
      var div = document.createElement('div');
      switch (tagName) {
        case 'THEAD':
        case 'TBODY':
          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
          depth = 2;
          break;
        case 'TR':
          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
          depth = 3;
          break;
        case 'TD':
          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
          depth = 4;
      }
      $A(element.childNodes).each(function(node){
        element.removeChild(node)
      });
      depth.times(function(){ div = div.firstChild });

      $A(div.childNodes).each(
        function(node){ element.appendChild(node) });
    } else {
      element.innerHTML = html.stripScripts();
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  }
};

Object.extend(Element, Element.Methods);

var _nativeExtensions = false;

if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
    var className = 'HTML' + tag + 'Element';
    if(window[className]) return;
    var klass = window[className] = {};
    klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
  });

Element.addMethods = function(methods) {
  Object.extend(Element.Methods, methods || {});

  function copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || false;
    var cache = Element.extend.cache;
    for (var property in methods) {
      var value = methods[property];
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = cache.findOrStore(value);
    }
  }

  if (typeof HTMLElement != 'undefined') {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
    copy(Form.Methods, HTMLFormElement.prototype);
    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
      copy(Form.Element.Methods, klass.prototype);
    });
    _nativeExtensions = true;
  }
}

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toUpperCase();
        if (['TBODY', 'TR'].include(tagName)) {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set($A(this).concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set($A(this).without(classNameToRemove).join(' '));
  },

  toString: function() {
    return $A(this).join(' ');
  }
};

Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },

  parseExpression: function() {
    function abort(message) { throw 'Parse error in selector: ' + message; }

    if (this.expression == '')  abort('empty expression');

    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
      params.attributes = params.attributes || [];
      params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
      expr = match[1];
    }

    if (expr == '*') return this.params.wildcard = true;

    while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
      modifier = match[1], clause = match[2], rest = match[3];
      switch (modifier) {
        case '#':       params.id = clause; break;
        case '.':       params.classNames.push(clause); break;
        case '':
        case undefined: params.tagName = clause.toUpperCase(); break;
        default:        abort(expr.inspect());
      }
      expr = rest;
    }

    if (expr.length > 0) abort(expr.inspect());
  },

  buildMatchExpression: function() {
    var params = this.params, conditions = [], clause;

    if (params.wildcard)
      conditions.push('true');
    if (clause = params.id)
      conditions.push('element.readAttribute("id") == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0, length = clause.length; i < length; i++)
        conditions.push('element.hasClassName(' + clause[i].inspect() + ')');
    if (clause = params.attributes) {
      clause.each(function(attribute) {
        var value = 'element.readAttribute(' + attribute.name.inspect() + ')';
        var splitValueBy = function(delimiter) {
          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
        }

        switch (attribute.operator) {
          case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
          case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
          case '|=':      conditions.push(
                            splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
                          ); break;
          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
          case '':
          case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break;
          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
        }
      });
    }

    return conditions.join(' && ');
  },

  compileMatcher: function() {
    this.match = new Function('element', 'if (!element.tagName) return false; \
      element = $(element); \
      return ' + this.buildMatchExpression());
  },

  findElements: function(scope) {
    var element;

    if (element = $(this.params.id))
      if (this.match(element))
        if (!scope || Element.childOf(element, scope))
          return [element];

    scope = (scope || document).getElementsByTagName(this.params.tagName || '*');

    var results = [];
    for (var i = 0, length = scope.length; i < length; i++)
      if (this.match(element = scope[i]))
        results.push(Element.extend(element));

    return results;
  },

  toString: function() {
    return this.expression;
  }
}

Object.extend(Selector, {
  matchElements: function(elements, expression) {
    var selector = new Selector(expression);
    return elements.select(selector.match.bind(selector)).map(Element.extend);
  },

  findElement: function(elements, expression, index) {
    if (typeof expression == 'number') index = expression, expression = false;
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    return expressions.map(function(expression) {
      return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) {
        var selector = new Selector(expr);
        return results.inject([], function(elements, result) {
          return elements.concat(selector.findElements(result || element));
        });
      });
    }).flatten();
  }
});

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, getHash) {
    var data = elements.inject({}, function(result, element) {
      if (!element.disabled && element.name) {
        var key = element.name, value = $(element).getValue();
        if (value != undefined) {
          if (result[key]) {
            if (result[key].constructor != Array) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return getHash ? data : Hash.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, getHash) {
    return Form.serializeElements(Form.getElements(form), getHash);
  },

  getElements: function(form) {
    return $A($(form).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
          elements.push(Element.extend(child));
        return elements;
      }
    );
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name) return $A(inputs).map(Element.extend);

    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) || (name && input.name != name))
        continue;
      matchingInputs.push(Element.extend(input));
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    form.getElements().each(function(element) {
      element.blur();
      element.disabled = 'true';
    });
    return form;
  },

  enable: function(form) {
    form = $(form);
    form.getElements().each(function(element) {
      element.disabled = '';
    });
    return form;
  },

  findFirstElement: function(form) {
    return $(form).getElements().find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    form.findFirstElement().activate();
    return form;
  }
}

Object.extend(Form, Form.Methods);

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
}

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    if (!element.disabled && element.name) {
      var value = element.getValue();
      if (value != undefined) {
        var pair = {};
        pair[element.name] = value;
        return Hash.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](element);
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select && ( element.tagName.toLowerCase() != 'input' ||
      !['button', 'reset', 'submit'].include(element.type) ) )
      element.select();
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.disabled = true;
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = false;
    return element;
  }
}

Object.extend(Form.Element, Form.Element.Methods);
var Field = Form.Element;
var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
      default:
        return Form.Element.Serializers.textarea(element);
    }
  },

  inputSelector: function(element) {
    return element.checked ? element.value : null;
  },

  textarea: function(element) {
    return element.value;
  },

  select: function(element) {
    return this[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var index = element.selectedIndex;
    return index >= 0 ? this.optionValue(element.options[index]) : null;
  },

  selectMany: function(element) {
    var values, length = element.length;
    if (!length) return null;

    for (var i = 0, values = []; i < length; i++) {
      var opt = element.options[i];
      if (opt.selected) values.push(this.optionValue(opt));
    }
    return values;
  },

  optionValue: function(opt) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
}

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    var changed = ('string' == typeof this.lastValue && 'string' == typeof value
      ? this.lastValue != value : String(this.lastValue) != String(value));
    if (changed) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    Form.getElements(this.element).each(this.registerCallback.bind(this));
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0, length = Event.observers.length; i < length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    Event._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try {
        element.detachEvent('on' + name, observer);
      } catch (e) {}
    }
  }
});

/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
  Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if(element.tagName=='BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!window.opera || element.tagName=='BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.width  = width + 'px';
    element.style.height = height + 'px';
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}

Element.addMethods();
function openWOAPopup (url) {
  myWindow = window.open(url, "WeltOnlineHilfe", "width=750,height=600,left=100,top=200,status=yes,scrollbars=yes,resizable=yes");
  myWindow.focus();
}

				function handleKeyUp(evt)
				{	
					evt = (evt) ? evt : ((event) ? event : null);
					id =  (evt.target) ? evt.target.id : evt.srcElement.id;
					value = (evt.target) ? evt.target.value : evt.srcElement.value;
					if (evt) {
						// check if return pressed
						if (evt.keyCode == 13) {
							
							deleteAllDefaultDateValues();
							form = document.getElementById("searchFormTop");
							form.submit();
						}
						else {
							syncDateField(id, value);
						}	
					}
					
				}	
				
				
				function readDates() {
					if (document.nf_period && document.nf_period.fromDate.value.length > 0) {
						document.searchFormTop.fromDate.value = document.nf_period.fromDate.value;
					}
					if (document.nf_period && document.nf_period.toDate.value.length > 0) {
						document.searchFormTop.toDate.value = document.nf_period.toDate.value;
					}
				}

				function readRessorts() {
				
					// read Ressorts wird durch die Umstellung der erweiterten Suche nun immer ausgeführt
					//if (document.getElementById('optionsDIV').style.display != 'none') {
						for (var x = 1; x < 14; x++) {
							if (document.getElementById('chk-1-'+x).checked == true) {
								document.searchFormTop.multiRessort.value += document.getElementById('chk-1-'+x).value + " ";
							}
						}
						if (document.searchFormTop.multiRessort.value.length > 0) {
							document.searchFormTop.multiRessort.value = document.searchFormTop.multiRessort.value.substring(0, document.searchFormTop.multiRessort.value.length - 1);
						}
					//}
				}

				function toggleRessort(group) {

					if (document.getElementById('chk-'+group).checked == true) {

						for (var x = 1; x < 20; x++) {
							if (document.getElementById('chk-'+group+'-'+x)) {
								document.getElementById('chk-'+group+'-'+x).setAttribute('checked', true);
								document.getElementById('chk-'+group+'-'+x).setAttribute('disabled', true);
							}
						}

					} else {

						for (var x = 1; x < 20; x++) {
							if (document.getElementById('chk-'+group+'-'+x)) {
								document.getElementById('chk-'+group+'-'+x).removeAttribute('checked');
								document.getElementById('chk-'+group+'-'+x).removeAttribute('disabled');
							}
						}									
					}
				}
				
				
				function selectRessort(group,check) {

					if (check == 'true') { 	// select all check boxes

						for (var x = 1; x < 20; x++) {
							if (document.getElementById('chk-'+group+'-'+x)) {
								document.getElementById('chk-'+group+'-'+x).checked = true;
							}
						}
						
						// deselect "Auswahl aufheben"
						document.getElementById('chk-2').checked = false;

					} else {				// deselect all check boxes

						for (var x = 1; x < 20; x++) {
							if (document.getElementById('chk-'+group+'-'+x)) {
								document.getElementById('chk-'+group+'-'+x).checked = false;
							}
						}
						
						// deselect "Alle auswählen"
						document.getElementById('chk-1').checked = false;
															
					}
				}
				
				function unselectMainCheckboxes() {
					document.getElementById('chk-1').checked = false;
					document.getElementById('chk-2').checked = false;
				}
				
				function switchToExtendedSearch() {
					// perform slide effect
					Effect.toggle('optionsDIV','slide', {duration:1}); 
					
					//toggle label simple search
					Element.toggle('labelSimpleSearch'); 
					
					//toggle label extended search
					Element.toggle('labelExtendedSearch');
					
					//deselect all ressorts 
					selectRessort(1,'false')
					
					//deselect timespane restrictions
					document.getElementById('chk-4-0').checked = true;
					
					//close all date picker windwows
					closeAllDatePickers ();

				
					
				}
				
				function switchToSimpleSearch() {
					// perform slide effect
					Effect.toggle('optionsDIV','slide', {duration:1});
					 
					//toggle label simple search 
					Element.toggle('labelSimpleSearch');
					
					//toggle label extended search 
					Element.toggle('labelExtendedSearch'); 
					
					//close all date picker windwows
					closeAllDatePickers ();
					
				}
				
				function closeAllDatePickersExceptFor (id) {

					var fromDate  = document.getElementById('datepicker-from_date');
					var toDate    = document.getElementById('datepicker-to_date');
					var fromDate2 = document.getElementById('datepicker-from_date2');
					var toDate2   = document.getElementById('datepicker-to_date2');
					
					if (fromDate  && id !='datepicker-from_date')  fromDate.style.display = 'none';
					if (toDate    && id !='datepicker-to_date')    toDate.style.display   = 'none';
					if (fromDate2 && id !='datepicker-from_date2') fromDate2.style.display= 'none';
					if (toDate2   && id !='datepicker-to_date2')   toDate2.style.display= 'none';
					
				}
				
				function closeAllDatePickers () {
					var fromDate  = document.getElementById('datepicker-from_date');
					var toDate    = document.getElementById('datepicker-to_date');
					var fromDate2 = document.getElementById('datepicker-from_date2');
					var toDate2   = document.getElementById('datepicker-to_date2');
					
					if (fromDate)  fromDate.style.display  = 'none';
					if (toDate)    toDate.style.display    = 'none';
					if (fromDate2) fromDate2.style.display = 'none';
					if (toDate2)   toDate2.style.display   = 'none';
				}
				
				
				function deleteDateInput(element) {
					if (element.value == 'tt.mm.jjjj') element.value = '';
				}
				
				
				function deleteAllDefaultDateValues() {
					if (document.getElementById('from_date') && document.getElementById('from_date').value  == 'tt.mm.jjjj') document.getElementById('from_date').value  = '';
					if (document.getElementById('to_date')	&& document.getElementById('to_date').value    == 'tt.mm.jjjj') document.getElementById('to_date').value    = '';
					if (document.getElementById('from_date2') && document.getElementById('from_date2').value == 'tt.mm.jjjj') document.getElementById('from_date2').value = '';
					if (document.getElementById('to_date2') && document.getElementById('to_date2').value   == 'tt.mm.jjjj') document.getElementById('to_date2').value   = '';
				}
				
				
				
				
				
				
				function moveDatePicker() {
					
					var anchor1 = document.getElementById('from_date2');
					var anchor2 = document.getElementById('to_date2');
					
					var newTopOffset1 = '';
					var newTopOffset2 = '';
					
					if (anchor1) newTopOffset1 = returnNewTopOffset(anchor1);
					if (anchor2) newTopOffset2 = returnNewTopOffset(anchor2);
					
					var datePicker1 = document.getElementById('datepicker-from_date2');
					var datePicker2 = document.getElementById('datepicker-to_date2');
					
					if (datePicker1) datePicker1.style.top = newTopOffset1 + 'px';
					if (datePicker2) datePicker2.style.top = newTopOffset2 + 'px';
					
					
  				
				}
				
				
				
				
				
				function returnNewTopOffset (obj, newTop) {
					var pos = {left:0, top:0};
					
					if(typeof obj.offsetLeft != 'undefined')
					{
					   while (obj)
					   {
					       pos.left += obj.offsetLeft;
					       pos.top += obj.offsetTop;
					       obj = obj.offsetParent;
					   }
					}
					else
					{
					   pos.left = obj.left ;
					   pos.top = obj.top ;
					}
					
					return pos.top;
				
				}
				

 /**
 * DatePicker widget using Prototype and Scriptaculous.
 * (c) 2007 Mathieu Jondet <mathieu@eulerian.com>
 * Eulerian Technologies
 *
 * DatePicker is freely distributable under the same terms as Prototype.
 *
 */

var datepickers = $H();

var DatePicker	= Class.create();

DatePicker.prototype	= {
  Version	: '0.9.2',
  _relative : null,
  _div		: null,
 _zindex	: 1,
 _keepFieldEmpty: false,
 _daysInMonth	: [31,28,31,30,31,30,31,31,30,31,30,31],
 /* language */
 _language	: 'fr',
 _language_month	: $H({
  'fr'	: [ 'Janvier', 'F&#233;vrier', 'Mars', 'Avril', 'Mai', 'Juin',
   'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'D&#233;cembre' ],
  'en'	: [ 'January', 'February', 'March', 'April', 'May',
   'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
  'sp'	: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
   'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
  'it'	: [ 'Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno',
   'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre' ],
  'de'	: [ 'Januar', 'Februar', 'M&#228;rz', 'April', 'Mai', 'Juni',
   'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ],
  'pt'	: [ 'Janeiro', 'Fevereiro', 'Mar&#231;o', 'Abril', 'Maio', 'Junho',
   'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro' ]
 }),
 _language_day	: $H({
  'fr'	: [ 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim' ],
  'en'	: [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ],
  'sp'	: [ 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'S&#224;b', 'Dom' ],
  'it'	: [ 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom' ],
  'de'	: [ 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So' ],
  'pt'	: [ 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'S&#225;', 'Dom' ]
 }),
 _language_close	: $H({
  'fr'	: 'fermer',
  'en'	: 'close',
  'sp'	: 'cierre',
  'it'	: 'fine',
  'de'	: 'Kalender schließen',
  'pt'	: 'fim'
 }),
 /* date manipulation */
 _todayDate	: new Date(),
 _date_regexp	: /^(\d{1,2})(\/|\.|\-)(\d{1,2})(?:\/|\.|\-)(\d{4})$/,
 _current_date	: null,
 _clickCallback	: Prototype.emptyFunction,
 _date_separator: '/',
 _id_datepicker	: null,
 /* positionning */
 _topOffset	: 0,
 _leftOffset	: 145,
 _isPositionned	: false,
 _relativePosition : true,
 /* return the name of current month in appropriate language */
 getMonthLocale	: function ( month ) {
  return	this._language_month[this._language][month];
 },
 getLocaleClose	: function () {
  return	this._language_close[this._language];
 },
  _initCurrentDate : function () {
  
  	// close all other open date pickers
  	closeAllDatePickersExceptFor(this._id_datepicker);
  	
    /* check if value in field is proper, set to today */
    this._current_date	= $F(this._relative);
    if ( !this._date_regexp.test(this._current_date) ) {
      var now	= new Date();
      var day	= this._leftpad_zero(now.getDate(), 2);
      var mon	= this._leftpad_zero(now.getMonth() + 1, 2);

	  if ( this._language == 'en' )
        this._current_date = mon+'.'+day+'.'+now.getFullYear();
      else
        this._current_date = day+'.'+mon+'.'+now.getFullYear();

   /* set the field value ? */
   if ( !this._keepFieldEmpty ) {
        syncDateField($(this._relative).id,this._current_date);
    	$(this._relative).setAttribute('value', this._current_date);
    }
  }
  var a_date_regexp	= this._current_date.match(this._date_regexp);
  /* fetch date separator as specified in option or via value */
  this._date_separator	= String(a_date_regexp[2]);
  /* check language */
  if ( this._language == 'en' ) {
   this._current_mon	= Number(a_date_regexp[1]) - 1;
   this._current_day	= Number(a_date_regexp[3]);
  } else {
   this._current_day	= Number(a_date_regexp[1]);
   this._current_mon	= Number(a_date_regexp[3]) - 1;
  }
  this._current_year	= Number(a_date_regexp[4]);
 },
 /* init */
 initialize	: function ( h_p ) {
 
  /* arguments */
  this._relative= h_p["relative"];
  if ( h_p["language"] )
   this._language = h_p["language"];
  this._zindex	= ( h_p["zindex"] ) ? parseInt(Number(h_p["zindex"])) : 1;
  if ( typeof(h_p["keepFieldEmpty"]) != 'undefined' )
   this._keepFieldEmpty	= h_p["keepFieldEmpty"];
  if ( typeof(h_p["clickCallback"]) == 'function' )
   this._clickCallback	= h_p["clickCallback"];
  if ( typeof(h_p["leftOffset"]) != 'undefined' )
   this._leftOffset	= parseInt(h_p["leftOffset"]);
  if ( typeof(h_p["topOffset"]) != 'undefined' )
   this._topOffset	= parseInt(h_p["topOffset"]);
  if ( typeof(h_p["relativePosition"]) != 'undefined' )
   this._relativePosition = h_p["relativePosition"];
  this._id_datepicker		= 'datepicker-'+this._relative;
  this._id_datepicker_prev	= this._id_datepicker+'-prev';
  this._id_datepicker_prev_year	= this._id_datepicker+'-prev-year';
  this._id_datepicker_next	= this._id_datepicker+'-next';
  this._id_datepicker_next_year	= this._id_datepicker+'-next-year';
  this._id_datepicker_hdr	= this._id_datepicker+'-header';
  this._id_datepicker_ftr	= this._id_datepicker+'-footer';

  /* build up calendar skel */
  this._div = Builder.node('div', {
    id : this._id_datepicker,
    className	: 'datepicker',
    style : 'display: none; z-index: '+this._zindex
   }, [
      /* header */
      Builder.node('div', { className : 'datepicker-header' }, [
       Builder.node('span', { id : this._id_datepicker_prev_year, style : 'cursor: pointer;' }, ' << '),
       Builder.node('span', { id : this._id_datepicker_prev, style : 'cursor: pointer;' }, ' < '),
       Builder.node('span', { id : this._id_datepicker_hdr }),
       Builder.node('span', { id : this._id_datepicker_next, style : 'cursor: pointer;' }, ' > '),
       Builder.node('span', { id : this._id_datepicker_next_year, style : 'cursor: pointer;' }, ' >> ')
      ]),
      /* calendar */
      Builder.node('div', { className : 'datepicker-calendar' }, [
       Builder.node('table', { id : this._id_datepicker+'-table' }) ]),
      /* footer */
      Builder.node('div', {
       id 	: this._id_datepicker_ftr,
       className: 'datepicker-footer' }, this.getLocaleClose() )
  ]);

  var body = document.getElementsByTagName("body").item(0);
  if (body) body.appendChild( this._div );
  /* init the date in field if needed */
  /* this._initCurrentDate(); */
  /* declare the observers for UI control */
  Event.observe($(this._id_datepicker_prev),'click', this.prevMonth.bindAsEventListener(this), false);
  Event.observe($(this._id_datepicker_prev_year),'click', this.prevYear.bindAsEventListener(this), false);
  Event.observe($(this._id_datepicker_next),'click', this.nextMonth.bindAsEventListener(this), false);
  Event.observe($(this._id_datepicker_next_year),'click', this.nextYear.bindAsEventListener(this), false);
  Event.observe($(this._id_datepicker_ftr),'click', this.close.bindAsEventListener(this), false);

    var datepickeropener = Builder.node('table',{className : "datepicker-opener-table"});
    	
	var con = Builder.node('tr',{},[
	    Builder.node('td',{className : "datepicker-opener", id : "datepicker-opener-"+this._relative, onclick : "document.getElementById('query').focus();"})
	]);
	// insert into TBODY
	if (datepickeropener.childNodes[0] != undefined) {
		datepickeropener.childNodes[0].appendChild(con);
	} else {
		datepickeropener.appendChild(con);
	}

	Event.observe(datepickeropener,'click', this.click.bindAsEventListener(this), false);

	this.insertAfter($(this._relative).parentNode,datepickeropener,$(this._relative));
 },

  insertAfter : function(parent, node, referenceNode) {
    parent.insertBefore(node, referenceNode.nextSibling);
  },

 /**
  * click	: called when input element is clicked
  */
 click : function () {
 
 	// move date picker divs
	moveDatePicker();
 
  if ( !this._isPositionned && this._relativePosition ) {
   /* position the datepicker relatively to element */
   var a_lt = this.positionedOffset($(this._relative));
   $(this._id_datepicker).setStyle({
    'left'	: Number(a_lt[0]+this._leftOffset)+'px',
    'top'	: Number(a_lt[1]+this._topOffset)+'px'
   });
   this._isPositionned	= true;
  }
  if ( !$(this._id_datepicker).visible() ) {
   this._initCurrentDate();
   this._redrawCalendar();
  }
  /* eval the clickCallback function */
  eval(this._clickCallback());
  /* Effect toggle to fade-in / fade-out the datepicker */
  new Effect.toggle(this._id_datepicker, 'appear', { duration : 0.2 });
 },

   positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
	  valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if(element.tagName=='BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') {
			// fix for divs;
			//break;
		}
      }
    } while (element);
    return [valueL, valueT];
  },

 /**
  * close	: called when the datepicker is closed
  */
 close : function () {
 
  // set focus to search query input field when user closes the calendar 
  document.getElementById('query').focus();
  
  new Effect.Fade(this._id_datepicker, { duration : 0.2 });
 },
 /**
  * setPosition	: set the position of the datepicker.
  *  param : t=top | l=left
  */
 setPosition	: function ( t, l ) {
  var h_pos	= { 'top' : '0px', 'left' : '0px' };
  if ( typeof(t) != 'undefined' )
   h_pos['top']	= Number(t)+this._topOffset+'px';
  if ( typeof(l) != 'undefined' )
   h_pos['left']= Number(l)+this._leftOffset+'px';
  $(this._id_datepicker).setStyle(h_pos);
  this._isPositionned	= true;
 },
 /**
  * _leftpad_zero : pad the provided string to given number of 0
  */
  /** CHECK toPaddedString: from http://dev.rubyonrails.org/changeset/6363 */
 _leftpad_zero	: function ( str, padToLength ) {
  var result	= '';
  for ( var i = 0; i < (padToLength - String(str).length); i++ )
   result	+= '0';
  return	result + str;
 },
 /**
  * _getMonthDays : given the year and month find the number of days.
  */
 _getMonthDays	: function ( year, month ) {
  if (((0 == (year%4)) &&
   ( (0 != (year%100)) || (0 == (year%400)))) && (month == 1))
   return 29;
  return this._daysInMonth[month];
 },
 /**
  * _buildCalendar	: draw the days array for current date
  */
 _buildCalendar		: function () {
  var _self	= this;
  var tbody	= document.createElement('tbody');
  /* generate day headers */
  var trDay	= document.createElement('tr');
  this._language_day[this._language].each( function ( item ) {
   var td	= document.createElement('td');
   td.innerHTML	= item;
   td.className	= 'wday';
   trDay.appendChild( td );
  });
  tbody.appendChild( trDay );
  /* generate the content of days */

  /* build-up days matrix */
  var a_d	= [
    [ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
   ,[ 0, 0, 0, 0, 0, 0, 0 ]
  ];
  /* set date at beginning of month to display */
  var d		= new Date(this._current_year, this._current_mon, 1, 12);
  /* start the day list on monday */
  var startIndex	= ( !d.getDay() ) ? 6 : d.getDay() - 1;
  var nbDaysInMonth	= this._getMonthDays(
    this._current_year, this._current_mon);
  var daysIndex		= 1;
  for ( var j = startIndex; j < 7; j++ ) {
   a_d[0][j] = {
     d : daysIndex
    ,m : this._current_mon
    ,y : this._current_year
   };
   daysIndex++;
  }
  var a_prevMY	= this._prevMonthYear();
  var nbDaysInMonthPrev	= this._getMonthDays(a_prevMY[1], a_prevMY[0]);
  for ( var j = 0; j < startIndex; j++ ) {
   a_d[0][j]	= {
     d : Number(nbDaysInMonthPrev - startIndex + j + 1)
    ,m : Number(a_prevMY[0])
    ,y : a_prevMY[1]
    ,c : 'outbound'
   };
  }
  var switchNextMonth	= false;
  var currentMonth	= this._current_mon;
  var currentYear	= this._current_year;
  for ( var i = 1; i < 6; i++ ) {
   for ( var j = 0; j < 7; j++ ) {
    a_d[i][j]	= {
      d : daysIndex
     ,m : currentMonth
     ,y : currentYear
     ,c : ( switchNextMonth ) ? 'outbound' : (
      ((daysIndex == this._todayDate.getDate()) &&
        (this._current_mon  == this._todayDate.getMonth()) &&
        (this._current_year == this._todayDate.getFullYear())) ? 'today' : null)
    };
    daysIndex++;
    /* if at the end of the month : reset counter */
    if ( daysIndex > nbDaysInMonth ) {
     daysIndex	= 1;
     switchNextMonth = true;
     if ( this._current_mon + 1 > 11 ) {
      currentMonth = 0;
      currentYear += 1;
     } else {
      currentMonth += 1;
     }
    }
   }
  }

  /* generate days for current date */
  for ( var i = 0; i < 6; i++ ) {
   var tr	= document.createElement('tr');
   for ( var j = 0; j < 7; j++ ) {
    var h_ij	= a_d[i][j];
    var td	= document.createElement('td');
    /* id is : datepicker-day-mon-year or depending on language other way */
    /* don't forget to add 1 on month for proper formmatting */
    if ( this._language == 'en' )
     var id	= $A([ this._relative, this._leftpad_zero((h_ij["m"] +1), 2),
       this._leftpad_zero(h_ij["d"], 2), h_ij["y"] ]).join('-');
     else
      var id	= $A([ this._relative, this._leftpad_zero(h_ij["d"], 2),
	this._leftpad_zero((h_ij["m"] + 1), 2), h_ij["y"] ]).join('-');
    /* set id and classname for cell if exists */
    td.setAttribute('id', id);
    if ( h_ij["c"] )
     td.className	= h_ij["c"];
    /* on onclick : rebuild date value from id of current cell */
    td.onclick	= function () {
     $(_self._relative).value = String($(this).readAttribute('id')
	).replace(_self._relative+'-','').replace(/-/g,_self._date_separator);
	syncDateField($(_self._relative).id,$(_self._relative).value);
     _self.close();
    };
    td.innerHTML= h_ij["d"];
    tr.appendChild( td );
   }
   tbody.appendChild( tr );
  }
  return	tbody;
 },
 /**
  * nextMonth	: redraw the calendar content for next month.
  */
 _nextMonthYear	: function () {
  var c_mon	= this._current_mon;
  var c_year	= this._current_year;
  if ( c_mon + 1 > 11 ) {
   c_mon	= 0;
   c_year	+= 1;
  } else {
   c_mon	+= 1;
  }
  return	[ c_mon, c_year ];
 },
 _nextYear	: function () {
  var c_mon	= this._current_mon;
  var c_year	= this._current_year;
  c_year	+= 1;
  return	[ c_mon, c_year ];
 },
 nextMonth	: function () {
  var a_next		= this._nextMonthYear();
  this._current_mon	= a_next[0];
  this._current_year 	= a_next[1];
  this._redrawCalendar();
 },
 nextYear	: function () {
  var a_next		= this._nextYear();
  this._current_mon	= a_next[0];
  this._current_year 	= a_next[1];
  this._redrawCalendar();
 },
 /**
  * prevMonth	: redraw the calendar content for previous month.
  */
 _prevMonthYear	: function () {
  var c_mon	= this._current_mon;
  var c_year	= this._current_year;
  if ( c_mon - 1 < 0 ) {
   c_mon	= 11;
   c_year	-= 1;
  } else {
   c_mon	-= 1;
  }
  return	[ c_mon, c_year ];
 },
 _prevYear	: function () {
  var c_mon	= this._current_mon;
  var c_year	= this._current_year;
  c_year	-= 1;
  return	[ c_mon, c_year ];
 },
 prevMonth	: function () {
  var a_prev		= this._prevMonthYear();
  this._current_mon	= a_prev[0];
  this._current_year 	= a_prev[1];
  this._redrawCalendar();
 },
 prevYear	: function () {
  var a_prev		= this._prevYear();
  this._current_mon	= a_prev[0];
  this._current_year 	= a_prev[1];
  this._redrawCalendar();
 },
 _redrawCalendar	: function () {
  this._setLocaleHdr();
  var table	= $(this._id_datepicker+'-table');
  try {
   while ( table.hasChildNodes() )
    table.removeChild(table.childNodes[0]);
  } catch ( e ) {}
  table.appendChild( this._buildCalendar() );
 },
 _setLocaleHdr	: function () {
  /* next link */
  var a_next = this._nextMonthYear();
  $(this._id_datepicker_next).setAttribute('title', this.getMonthLocale(a_next[0])+' '+a_next[1]);
  /* prev link */
  var a_prev = this._prevMonthYear();
  $(this._id_datepicker_prev).setAttribute('title', this.getMonthLocale(a_prev[0])+' '+a_prev[1]);
  /* header */
  $(this._id_datepicker_hdr).update('&nbsp;&nbsp;&nbsp;'+this.getMonthLocale(this._current_mon)+'&nbsp;'+this._current_year+'&nbsp;&nbsp;&nbsp;');
 }
};

function initDatepickers_alt() {
	$$("*").findAll(function(node) {
     return Element.hasClassName(node,'date');
   }).each(function(node) {
   	 datepickers[node.id] = new DatePicker({
      relative : node.id,
      language : 'de'
      });
   });
}

function initDatepickers() {
			
	 node_1 = document.getElementById('to_date');
	 node_2 = document.getElementById('from_date');
	 node_3 = document.getElementById('to_date2');
	 node_4 = document.getElementById('from_date2');
	 
	 if (node_1) buildCalendarNode(node_1);
	 if (node_2) buildCalendarNode(node_2);
	 if (node_3) buildCalendarNode(node_3);
	 if (node_4) buildCalendarNode(node_4);
         
}

function buildCalendarNode(element) {
	datepickers[element.id] = new DatePicker({
      relative : element.id,
      language : 'de'
    });
}

function syncDateField(id, value) {
	switch (id) {
		case 'from_date': if(document.getElementById('from_date2')) document.getElementById('from_date2').value=value; break
		case 'from_date2':if(document.getElementById('from_date'))  document.getElementById('from_date').value=value; break
		case 'to_date':if(document.getElementById('to_date2'))  document.getElementById('to_date2').value=value; break
		case 'to_date2':if(document.getElementById('to_date'))  document.getElementById('to_date').value=value; break
		default: console.log('unknown id:'+id);
	}
}




Event.observe(window, 'load', initDatepickers, false);



<!-- Autocompletion script -->
/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.4.0
*/
if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C<A.length;C=C+1){D=A[C].split(".");E=YAHOO;for(B=(D[0]=="YAHOO")?1:0;B<D.length;B=B+1){E[D[B]]=E[D[B]]||{};E=E[D[B]];}}return E;};YAHOO.log=function(D,A,C){var B=YAHOO.widget.Logger;if(B&&B.log){return B.log(D,A,C);}else{return false;}};YAHOO.register=function(A,E,D){var I=YAHOO.env.modules;if(!I[A]){I[A]={versions:[],builds:[]};}var B=I[A],H=D.version,G=D.build,F=YAHOO.env.listeners;B.name=A;B.version=H;B.build=G;B.versions.push(H);B.builds.push(G);B.mainClass=E;for(var C=0;C<F.length;C=C+1){F[C](B);}if(E){E.VERSION=H;E.BUILD=G;}else{YAHOO.log("mainClass is undefined for module "+A,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(A){return YAHOO.env.modules[A]||null;};YAHOO.env.ua=function(){var C={ie:0,opera:0,gecko:0,webkit:0,mobile:null};var B=navigator.userAgent,A;if((/KHTML/).test(B)){C.webkit=1;}A=B.match(/AppleWebKit\/([^\s]*)/);if(A&&A[1]){C.webkit=parseFloat(A[1]);if(/ Mobile\//.test(B)){C.mobile="Apple";}else{A=B.match(/NokiaN[^\/]*/);if(A){C.mobile=A[0];}}}if(!C.webkit){A=B.match(/Opera[\s\/]([^\s]*)/);if(A&&A[1]){C.opera=parseFloat(A[1]);A=B.match(/Opera Mini[^;]*/);if(A){C.mobile=A[0];}}else{A=B.match(/MSIE\s([^;]*)/);if(A&&A[1]){C.ie=parseFloat(A[1]);}else{A=B.match(/Gecko\/([^\s]*)/);if(A){C.gecko=1;A=B.match(/rv:([^\s\)]*)/);if(A&&A[1]){C.gecko=parseFloat(A[1]);}}}}}return C;}();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var B=YAHOO_config.listener,A=YAHOO.env.listeners,D=true,C;if(B){for(C=0;C<A.length;C=C+1){if(A[C]==B){D=false;break;}}if(D){A.push(B);}}}})();YAHOO.lang=YAHOO.lang||{isArray:function(B){if(B){var A=YAHOO.lang;return A.isNumber(B.length)&&A.isFunction(B.splice);}return false;},isBoolean:function(A){return typeof A==="boolean";},isFunction:function(A){return typeof A==="function";},isNull:function(A){return A===null;},isNumber:function(A){return typeof A==="number"&&isFinite(A);},isObject:function(A){return(A&&(typeof A==="object"||YAHOO.lang.isFunction(A)))||false;},isString:function(A){return typeof A==="string";},isUndefined:function(A){return typeof A==="undefined";},hasOwnProperty:function(A,B){if(Object.prototype.hasOwnProperty){return A.hasOwnProperty(B);}return !YAHOO.lang.isUndefined(A[B])&&A.constructor.prototype[B]!==A[B];},_IEEnumFix:function(C,B){if(YAHOO.env.ua.ie){var E=["toString","valueOf"],A;for(A=0;A<E.length;A=A+1){var F=E[A],D=B[F];if(YAHOO.lang.isFunction(D)&&D!=Object.prototype[F]){C[F]=D;}}}},extend:function(D,E,C){if(!E||!D){throw new Error("YAHOO.lang.extend failed, please check that all dependencies are included.");}var B=function(){};B.prototype=E.prototype;D.prototype=new B();D.prototype.constructor=D;D.superclass=E.prototype;if(E.prototype.constructor==Object.prototype.constructor){E.prototype.constructor=E;}if(C){for(var A in C){D.prototype[A]=C[A];}YAHOO.lang._IEEnumFix(D.prototype,C);}},augmentObject:function(E,D){if(!D||!E){throw new Error("Absorb failed, verify dependencies.");}var A=arguments,C,F,B=A[2];if(B&&B!==true){for(C=2;C<A.length;C=C+1){E[A[C]]=D[A[C]];}}else{for(F in D){if(B||!E[F]){E[F]=D[F];}}YAHOO.lang._IEEnumFix(E,D);}},augmentProto:function(D,C){if(!C||!D){throw new Error("Augment failed, verify dependencies.");}var A=[D.prototype,C.prototype];for(var B=2;B<arguments.length;B=B+1){A.push(arguments[B]);}YAHOO.lang.augmentObject.apply(this,A);},dump:function(A,G){var C=YAHOO.lang,D,F,I=[],J="{...}",B="f(){...}",H=", ",E=" => ";if(!C.isObject(A)){return A+"";}else{if(A instanceof Date||("nodeType" in A&&"tagName" in A)){return A;}else{if(C.isFunction(A)){return B;}}}G=(C.isNumber(G))?G:3;if(C.isArray(A)){I.push("[");for(D=0,F=A.length;D<F;D=D+1){if(C.isObject(A[D])){I.push((G>0)?C.dump(A[D],G-1):J);}else{I.push(A[D]);}I.push(H);}if(I.length>1){I.pop();}I.push("]");}else{I.push("{");for(D in A){if(C.hasOwnProperty(A,D)){I.push(D+E);if(C.isObject(A[D])){I.push((G>0)?C.dump(A[D],G-1):J);}else{I.push(A[D]);}I.push(H);}}if(I.length>1){I.pop();}I.push("}");}return I.join("");},substitute:function(Q,B,J){var G,F,E,M,N,P,D=YAHOO.lang,L=[],C,H="dump",K=" ",A="{",O="}";for(;;){G=Q.lastIndexOf(A);if(G<0){break;}F=Q.indexOf(O,G);if(G+1>=F){break;}C=Q.substring(G+1,F);M=C;P=null;E=M.indexOf(K);if(E>-1){P=M.substring(E+1);M=M.substring(0,E);}N=B[M];if(J){N=J(M,N,P);}if(D.isObject(N)){if(D.isArray(N)){N=D.dump(N,parseInt(P,10));}else{P=P||"";var I=P.indexOf(H);if(I>-1){P=P.substring(4);}if(N.toString===Object.prototype.toString||I>-1){N=D.dump(N,parseInt(P,10));}else{N=N.toString();}}}else{if(!D.isString(N)&&!D.isNumber(N)){N="~-"+L.length+"-~";L[L.length]=C;}}Q=Q.substring(0,G)+N+Q.substring(F+1);}for(G=L.length-1;G>=0;G=G-1){Q=Q.replace(new RegExp("~-"+G+"-~"),"{"+L[G]+"}","g");}return Q;},trim:function(A){try{return A.replace(/^\s+|\s+$/g,"");}catch(B){return A;}},merge:function(){var D={},B=arguments;for(var C=0,A=B.length;C<A;C=C+1){YAHOO.lang.augmentObject(D,B[C],true);}return D;},later:function(H,B,I,D,E){H=H||0;B=B||{};var C=I,G=D,F,A;if(YAHOO.lang.isString(I)){C=B[I];}if(!C){throw new TypeError("method undefined");}if(!YAHOO.lang.isArray(G)){G=[D];}F=function(){C.apply(B,G);};A=(E)?setInterval(F,H):setTimeout(F,H);return{interval:E,cancel:function(){if(this.interval){clearInterval(A);}else{clearTimeout(A);}}};},isValue:function(B){var A=YAHOO.lang;return(A.isObject(B)||A.isString(B)||A.isNumber(B)||A.isBoolean(B));}};YAHOO.util.Lang=YAHOO.lang;YAHOO.lang.augment=YAHOO.lang.augmentProto;YAHOO.augment=YAHOO.lang.augmentProto;YAHOO.extend=YAHOO.lang.extend;YAHOO.register("yahoo",YAHOO,{version:"2.4.0",build:"733"});(function(){var B=YAHOO.util,L,J,H=0,K={},F={},N=window.document;var C=YAHOO.env.ua.opera,M=YAHOO.env.ua.webkit,A=YAHOO.env.ua.gecko,G=YAHOO.env.ua.ie;var E={HYPHEN:/(-[a-z])/i,ROOT_TAG:/^body|html$/i};var O=function(Q){if(!E.HYPHEN.test(Q)){return Q;}if(K[Q]){return K[Q];}var R=Q;while(E.HYPHEN.exec(R)){R=R.replace(RegExp.$1,RegExp.$1.substr(1).toUpperCase());}K[Q]=R;return R;};var P=function(R){var Q=F[R];if(!Q){Q=new RegExp("(?:^|\\s+)"+R+"(?:\\s+|$)");F[R]=Q;}return Q;};if(N.defaultView&&N.defaultView.getComputedStyle){L=function(Q,T){var S=null;if(T=="float"){T="cssFloat";}var R=N.defaultView.getComputedStyle(Q,"");if(R){S=R[O(T)];}return Q.style[T]||S;};}else{if(N.documentElement.currentStyle&&G){L=function(Q,S){switch(O(S)){case"opacity":var U=100;try{U=Q.filters["DXImageTransform.Microsoft.Alpha"].opacity;}catch(T){try{U=Q.filters("alpha").opacity;}catch(T){}}return U/100;case"float":S="styleFloat";default:var R=Q.currentStyle?Q.currentStyle[S]:null;return(Q.style[S]||R);}};}else{L=function(Q,R){return Q.style[R];};}}if(G){J=function(Q,R,S){switch(R){case"opacity":if(YAHOO.lang.isString(Q.style.filter)){Q.style.filter="alpha(opacity="+S*100+")";if(!Q.currentStyle||!Q.currentStyle.hasLayout){Q.style.zoom=1;}}break;case"float":R="styleFloat";default:Q.style[R]=S;}};}else{J=function(Q,R,S){if(R=="float"){R="cssFloat";}Q.style[R]=S;};}var D=function(Q,R){return Q&&Q.nodeType==1&&(!R||R(Q));};YAHOO.util.Dom={get:function(S){if(S&&(S.tagName||S.item)){return S;}if(YAHOO.lang.isString(S)||!S){return N.getElementById(S);}if(S.length!==undefined){var T=[];for(var R=0,Q=S.length;R<Q;++R){T[T.length]=B.Dom.get(S[R]);}return T;}return S;},getStyle:function(Q,S){S=O(S);var R=function(T){return L(T,S);};return B.Dom.batch(Q,R,B.Dom,true);},setStyle:function(Q,S,T){S=O(S);var R=function(U){J(U,S,T);};B.Dom.batch(Q,R,B.Dom,true);},getXY:function(Q){var R=function(S){if((S.parentNode===null||S.offsetParent===null||this.getStyle(S,"display")=="none")&&S!=S.ownerDocument.body){return false;}return I(S);};return B.Dom.batch(Q,R,B.Dom,true);},getX:function(Q){var R=function(S){return B.Dom.getXY(S)[0];};return B.Dom.batch(Q,R,B.Dom,true);},getY:function(Q){var R=function(S){return B.Dom.getXY(S)[1];};return B.Dom.batch(Q,R,B.Dom,true);},setXY:function(Q,T,S){var R=function(W){var V=this.getStyle(W,"position");if(V=="static"){this.setStyle(W,"position","relative");V="relative";}var Y=this.getXY(W);if(Y===false){return false;}var X=[parseInt(this.getStyle(W,"left"),10),parseInt(this.getStyle(W,"top"),10)];if(isNaN(X[0])){X[0]=(V=="relative")?0:W.offsetLeft;}if(isNaN(X[1])){X[1]=(V=="relative")?0:W.offsetTop;}if(T[0]!==null){W.style.left=T[0]-Y[0]+X[0]+"px";}if(T[1]!==null){W.style.top=T[1]-Y[1]+X[1]+"px";}if(!S){var U=this.getXY(W);if((T[0]!==null&&U[0]!=T[0])||(T[1]!==null&&U[1]!=T[1])){this.setXY(W,T,true);}}};B.Dom.batch(Q,R,B.Dom,true);},setX:function(R,Q){B.Dom.setXY(R,[Q,null]);},setY:function(Q,R){B.Dom.setXY(Q,[null,R]);},getRegion:function(Q){var R=function(S){if((S.parentNode===null||S.offsetParent===null||this.getStyle(S,"display")=="none")&&S!=N.body){return false;}var T=B.Region.getRegion(S);return T;};return B.Dom.batch(Q,R,B.Dom,true);},getClientWidth:function(){return B.Dom.getViewportWidth();},getClientHeight:function(){return B.Dom.getViewportHeight();},getElementsByClassName:function(U,Y,V,W){Y=Y||"*";V=(V)?B.Dom.get(V):null||N;if(!V){return[];}var R=[],Q=V.getElementsByTagName(Y),X=P(U);for(var S=0,T=Q.length;S<T;++S){if(X.test(Q[S].className)){R[R.length]=Q[S];if(W){W.call(Q[S],Q[S]);}}}return R;},hasClass:function(S,R){var Q=P(R);var T=function(U){return Q.test(U.className);};return B.Dom.batch(S,T,B.Dom,true);},addClass:function(R,Q){var S=function(T){if(this.hasClass(T,Q)){return false;}T.className=YAHOO.lang.trim([T.className,Q].join(" "));return true;};return B.Dom.batch(R,S,B.Dom,true);},removeClass:function(S,R){var Q=P(R);var T=function(U){if(!this.hasClass(U,R)){return false;}var V=U.className;U.className=V.replace(Q," ");if(this.hasClass(U,R)){this.removeClass(U,R);}U.className=YAHOO.lang.trim(U.className);return true;};return B.Dom.batch(S,T,B.Dom,true);},replaceClass:function(T,R,Q){if(!Q||R===Q){return false;}var S=P(R);var U=function(V){if(!this.hasClass(V,R)){this.addClass(V,Q);return true;}V.className=V.className.replace(S," "+Q+" ");if(this.hasClass(V,R)){this.replaceClass(V,R,Q);}V.className=YAHOO.lang.trim(V.className);return true;};return B.Dom.batch(T,U,B.Dom,true);},generateId:function(Q,S){S=S||"yui-gen";var R=function(T){if(T&&T.id){return T.id;}var U=S+H++;if(T){T.id=U;}return U;};return B.Dom.batch(Q,R,B.Dom,true)||R.apply(B.Dom,arguments);},isAncestor:function(Q,R){Q=B.Dom.get(Q);R=B.Dom.get(R);if(!Q||!R){return false;}if(Q.contains&&R.nodeType&&!M){return Q.contains(R);}else{if(Q.compareDocumentPosition&&R.nodeType){return !!(Q.compareDocumentPosition(R)&16);}else{if(R.nodeType){return !!this.getAncestorBy(R,function(S){return S==Q;});}}}return false;},inDocument:function(Q){return this.isAncestor(N.documentElement,Q);},getElementsBy:function(X,R,S,U){R=R||"*";S=(S)?B.Dom.get(S):null||N;if(!S){return[];}var T=[],W=S.getElementsByTagName(R);for(var V=0,Q=W.length;V<Q;++V){if(X(W[V])){T[T.length]=W[V];if(U){U(W[V]);}}}return T;},batch:function(U,X,W,S){U=(U&&(U.tagName||U.item))?U:B.Dom.get(U);if(!U||!X){return false;}var T=(S)?W:window;if(U.tagName||U.length===undefined){return X.call(T,U,W);}var V=[];for(var R=0,Q=U.length;R<Q;++R){V[V.length]=X.call(T,U[R],W);}return V;},getDocumentHeight:function(){var R=(N.compatMode!="CSS1Compat")?N.body.scrollHeight:N.documentElement.scrollHeight;var Q=Math.max(R,B.Dom.getViewportHeight());return Q;},getDocumentWidth:function(){var R=(N.compatMode!="CSS1Compat")?N.body.scrollWidth:N.documentElement.scrollWidth;var Q=Math.max(R,B.Dom.getViewportWidth());return Q;},getViewportHeight:function(){var Q=self.innerHeight;var R=N.compatMode;if((R||G)&&!C){Q=(R=="CSS1Compat")?N.documentElement.clientHeight:N.body.clientHeight;
}return Q;},getViewportWidth:function(){var Q=self.innerWidth;var R=N.compatMode;if(R||G){Q=(R=="CSS1Compat")?N.documentElement.clientWidth:N.body.clientWidth;}return Q;},getAncestorBy:function(Q,R){while(Q=Q.parentNode){if(D(Q,R)){return Q;}}return null;},getAncestorByClassName:function(R,Q){R=B.Dom.get(R);if(!R){return null;}var S=function(T){return B.Dom.hasClass(T,Q);};return B.Dom.getAncestorBy(R,S);},getAncestorByTagName:function(R,Q){R=B.Dom.get(R);if(!R){return null;}var S=function(T){return T.tagName&&T.tagName.toUpperCase()==Q.toUpperCase();};return B.Dom.getAncestorBy(R,S);},getPreviousSiblingBy:function(Q,R){while(Q){Q=Q.previousSibling;if(D(Q,R)){return Q;}}return null;},getPreviousSibling:function(Q){Q=B.Dom.get(Q);if(!Q){return null;}return B.Dom.getPreviousSiblingBy(Q);},getNextSiblingBy:function(Q,R){while(Q){Q=Q.nextSibling;if(D(Q,R)){return Q;}}return null;},getNextSibling:function(Q){Q=B.Dom.get(Q);if(!Q){return null;}return B.Dom.getNextSiblingBy(Q);},getFirstChildBy:function(Q,S){var R=(D(Q.firstChild,S))?Q.firstChild:null;return R||B.Dom.getNextSiblingBy(Q.firstChild,S);},getFirstChild:function(Q,R){Q=B.Dom.get(Q);if(!Q){return null;}return B.Dom.getFirstChildBy(Q);},getLastChildBy:function(Q,S){if(!Q){return null;}var R=(D(Q.lastChild,S))?Q.lastChild:null;return R||B.Dom.getPreviousSiblingBy(Q.lastChild,S);},getLastChild:function(Q){Q=B.Dom.get(Q);return B.Dom.getLastChildBy(Q);},getChildrenBy:function(R,T){var S=B.Dom.getFirstChildBy(R,T);var Q=S?[S]:[];B.Dom.getNextSiblingBy(S,function(U){if(!T||T(U)){Q[Q.length]=U;}return false;});return Q;},getChildren:function(Q){Q=B.Dom.get(Q);if(!Q){}return B.Dom.getChildrenBy(Q);},getDocumentScrollLeft:function(Q){Q=Q||N;return Math.max(Q.documentElement.scrollLeft,Q.body.scrollLeft);},getDocumentScrollTop:function(Q){Q=Q||N;return Math.max(Q.documentElement.scrollTop,Q.body.scrollTop);},insertBefore:function(R,Q){R=B.Dom.get(R);Q=B.Dom.get(Q);if(!R||!Q||!Q.parentNode){return null;}return Q.parentNode.insertBefore(R,Q);},insertAfter:function(R,Q){R=B.Dom.get(R);Q=B.Dom.get(Q);if(!R||!Q||!Q.parentNode){return null;}if(Q.nextSibling){return Q.parentNode.insertBefore(R,Q.nextSibling);}else{return Q.parentNode.appendChild(R);}},getClientRegion:function(){var S=B.Dom.getDocumentScrollTop(),R=B.Dom.getDocumentScrollLeft(),T=B.Dom.getViewportWidth()+R,Q=B.Dom.getViewportHeight()+S;return new B.Region(S,T,Q,R);}};var I=function(){if(N.documentElement.getBoundingClientRect){return function(R){var S=R.getBoundingClientRect();var Q=R.ownerDocument;return[S.left+B.Dom.getDocumentScrollLeft(Q),S.top+B.Dom.getDocumentScrollTop(Q)];};}else{return function(S){var T=[S.offsetLeft,S.offsetTop];var R=S.offsetParent;var Q=(M&&B.Dom.getStyle(S,"position")=="absolute"&&S.offsetParent==S.ownerDocument.body);if(R!=S){while(R){T[0]+=R.offsetLeft;T[1]+=R.offsetTop;if(!Q&&M&&B.Dom.getStyle(R,"position")=="absolute"){Q=true;}R=R.offsetParent;}}if(Q){T[0]-=S.ownerDocument.body.offsetLeft;T[1]-=S.ownerDocument.body.offsetTop;}R=S.parentNode;while(R.tagName&&!E.ROOT_TAG.test(R.tagName)){if(B.Dom.getStyle(R,"display").search(/^inline|table-row.*$/i)){T[0]-=R.scrollLeft;T[1]-=R.scrollTop;}R=R.parentNode;}return T;};}}();})();YAHOO.util.Region=function(C,D,A,B){this.top=C;this[1]=C;this.right=D;this.bottom=A;this.left=B;this[0]=B;};YAHOO.util.Region.prototype.contains=function(A){return(A.left>=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top);var D=Math.min(this.right,E.right);var A=Math.min(this.bottom,E.bottom);var B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top);var D=Math.max(this.right,E.right);var A=Math.max(this.bottom,E.bottom);var B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D);var C=F[1];var E=F[0]+D.offsetWidth;var A=F[1]+D.offsetHeight;var B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}this.x=this.right=this.left=this[0]=A;this.y=this.top=this.bottom=this[1]=B;};YAHOO.util.Point.prototype=new YAHOO.util.Region();YAHOO.register("dom",YAHOO.util.Dom,{version:"2.4.0",build:"733"});YAHOO.util.CustomEvent=function(D,B,C,A){this.type=D;this.scope=B||window;this.silent=C;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var E="_YUICEOnSubscribe";if(D!==E){this.subscribeEvent=new YAHOO.util.CustomEvent(E,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(B,C,A){if(!B){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(B,C,A);}this.subscribers.push(new YAHOO.util.Subscriber(B,C,A));},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B<A;++B){var C=this.subscribers[B];if(C&&C.contains(D,F)){this._delete(B);E=true;}}return E;},fire:function(){var D=this.subscribers.length;if(!D&&this.silent){return true;}var G=[],F=true,C,H=false;for(C=0;C<arguments.length;++C){G.push(arguments[C]);}if(!this.silent){}for(C=0;C<D;++C){var K=this.subscribers[C];if(!K){H=true;}else{if(!this.silent){}var J=K.getScope(this.scope);if(this.signature==YAHOO.util.CustomEvent.FLAT){var A=null;if(G.length>0){A=G[0];}try{F=K.fn.call(J,A,K.obj);}catch(E){this.lastError=E;}}else{try{F=K.fn.call(J,this.type,G,K.obj);}catch(E){this.lastError=E;}}if(false===F){if(!this.silent){}return false;}}}if(H){var I=[],B=this.subscribers;for(C=0,D=B.length;C<D;C=C+1){I.push(B[C]);}this.subscribers=I;}return true;},unsubscribeAll:function(){for(var B=0,A=this.subscribers.length;B<A;++B){this._delete(A-1-B);}this.subscribers=[];return B;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers[A]=null;},toString:function(){return"CustomEvent: '"+this.type+"', scope: "+this.scope;}};YAHOO.util.Subscriber=function(B,C,A){this.fn=B;this.obj=YAHOO.lang.isUndefined(C)?null:C;this.override=A;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.override){if(this.override===true){return this.obj;}else{return this.override;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", override: "+(this.override||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var H=false;var I=[];var J=[];var G=[];var E=[];var C=0;var F=[];var B=[];var A=0;var D={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9};return{POLL_RETRYS:4000,POLL_INTERVAL:10,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:YAHOO.env.ua.ie,_interval:null,_dri:null,DOMReady:false,startInterval:function(){if(!this._interval){var K=this;var L=function(){K._tryPreloadAttach();};this._interval=setInterval(L,this.POLL_INTERVAL);}},onAvailable:function(P,M,Q,O,N){var K=(YAHOO.lang.isString(P))?[P]:P;for(var L=0;L<K.length;L=L+1){F.push({id:K[L],fn:M,obj:Q,override:O,checkReady:N});}C=this.POLL_RETRYS;this.startInterval();},onContentReady:function(M,K,N,L){this.onAvailable(M,K,N,L,true);},onDOMReady:function(K,M,L){if(this.DOMReady){setTimeout(function(){var N=window;if(L){if(L===true){N=M;}else{N=L;}}K.call(N,"DOMReady",[],M);},0);}else{this.DOMReadyEvent.subscribe(K,M,L);}},addListener:function(M,K,V,Q,L){if(!V||!V.call){return false;}if(this._isValidCollection(M)){var W=true;for(var R=0,T=M.length;R<T;++R){W=this.on(M[R],K,V,Q,L)&&W;}return W;}else{if(YAHOO.lang.isString(M)){var P=this.getEl(M);if(P){M=P;}else{this.onAvailable(M,function(){YAHOO.util.Event.on(M,K,V,Q,L);});return true;}}}if(!M){return false;}if("unload"==K&&Q!==this){J[J.length]=[M,K,V,Q,L];return true;}var Y=M;if(L){if(L===true){Y=Q;}else{Y=L;}}var N=function(Z){return V.call(Y,YAHOO.util.Event.getEvent(Z,M),Q);};var X=[M,K,V,N,Y,Q,L];var S=I.length;I[S]=X;if(this.useLegacyEvent(M,K)){var O=this.getLegacyIndex(M,K);if(O==-1||M!=G[O][0]){O=G.length;B[M.id+K]=O;G[O]=[M,K,M["on"+K]];E[O]=[];M["on"+K]=function(Z){YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(Z),O);};}E[O].push(X);}else{try{this._simpleAdd(M,K,N,false);}catch(U){this.lastError=U;this.removeListener(M,K,V);return false;}}return true;},fireLegacyEvent:function(O,M){var Q=true,K,S,R,T,P;S=E[M];for(var L=0,N=S.length;L<N;++L){R=S[L];if(R&&R[this.WFN]){T=R[this.ADJ_SCOPE];P=R[this.WFN].call(T,O);Q=(Q&&P);}}K=G[M];if(K&&K[2]){K[2](O);}return Q;},getLegacyIndex:function(L,M){var K=this.generateId(L)+M;if(typeof B[K]=="undefined"){return -1;}else{return B[K];}},useLegacyEvent:function(L,M){if(this.webkit&&("click"==M||"dblclick"==M)){var K=parseInt(this.webkit,10);if(!isNaN(K)&&K<418){return true;}}return false;},removeListener:function(L,K,T){var O,R,V;if(typeof L=="string"){L=this.getEl(L);}else{if(this._isValidCollection(L)){var U=true;for(O=0,R=L.length;O<R;++O){U=(this.removeListener(L[O],K,T)&&U);}return U;}}if(!T||!T.call){return this.purgeElement(L,false,K);}if("unload"==K){for(O=0,R=J.length;O<R;O++){V=J[O];if(V&&V[0]==L&&V[1]==K&&V[2]==T){J[O]=null;return true;}}return false;}var P=null;var Q=arguments[3];if("undefined"===typeof Q){Q=this._getCacheIndex(L,K,T);}if(Q>=0){P=I[Q];}if(!L||!P){return false;}if(this.useLegacyEvent(L,K)){var N=this.getLegacyIndex(L,K);var M=E[N];if(M){for(O=0,R=M.length;O<R;++O){V=M[O];if(V&&V[this.EL]==L&&V[this.TYPE]==K&&V[this.FN]==T){M[O]=null;break;}}}}else{try{this._simpleRemove(L,K,P[this.WFN],false);}catch(S){this.lastError=S;return false;}}delete I[Q][this.WFN];delete I[Q][this.FN];I[Q]=null;return true;},getTarget:function(M,L){var K=M.target||M.srcElement;return this.resolveTextNode(K);},resolveTextNode:function(K){if(K&&3==K.nodeType){return K.parentNode;}else{return K;}},getPageX:function(L){var K=L.pageX;if(!K&&0!==K){K=L.clientX||0;if(this.isIE){K+=this._getScrollLeft();}}return K;},getPageY:function(K){var L=K.pageY;if(!L&&0!==L){L=K.clientY||0;if(this.isIE){L+=this._getScrollTop();}}return L;},getXY:function(K){return[this.getPageX(K),this.getPageY(K)];
},getRelatedTarget:function(L){var K=L.relatedTarget;if(!K){if(L.type=="mouseout"){K=L.toElement;}else{if(L.type=="mouseover"){K=L.fromElement;}}}return this.resolveTextNode(K);},getTime:function(M){if(!M.time){var L=new Date().getTime();try{M.time=L;}catch(K){this.lastError=K;return L;}}return M.time;},stopEvent:function(K){this.stopPropagation(K);this.preventDefault(K);},stopPropagation:function(K){if(K.stopPropagation){K.stopPropagation();}else{K.cancelBubble=true;}},preventDefault:function(K){if(K.preventDefault){K.preventDefault();}else{K.returnValue=false;}},getEvent:function(M,K){var L=M||window.event;if(!L){var N=this.getEvent.caller;while(N){L=N.arguments[0];if(L&&Event==L.constructor){break;}N=N.caller;}}return L;},getCharCode:function(L){var K=L.keyCode||L.charCode||0;if(YAHOO.env.ua.webkit&&(K in D)){K=D[K];}return K;},_getCacheIndex:function(O,P,N){for(var M=0,L=I.length;M<L;++M){var K=I[M];if(K&&K[this.FN]==N&&K[this.EL]==O&&K[this.TYPE]==P){return M;}}return -1;},generateId:function(K){var L=K.id;if(!L){L="yuievtautoid-"+A;++A;K.id=L;}return L;},_isValidCollection:function(L){try{return(L&&typeof L!=="string"&&L.length&&!L.tagName&&!L.alert&&typeof L[0]!=="undefined");}catch(K){return false;}},elCache:{},getEl:function(K){return(typeof K==="string")?document.getElementById(K):K;},clearCache:function(){},DOMReadyEvent:new YAHOO.util.CustomEvent("DOMReady",this),_load:function(L){if(!H){H=true;var K=YAHOO.util.Event;K._ready();K._tryPreloadAttach();}},_ready:function(L){var K=YAHOO.util.Event;if(!K.DOMReady){K.DOMReady=true;K.DOMReadyEvent.fire();K._simpleRemove(document,"DOMContentLoaded",K._ready);}},_tryPreloadAttach:function(){if(this.locked){return false;}if(this.isIE){if(!this.DOMReady){this.startInterval();return false;}}this.locked=true;var P=!H;if(!P){P=(C>0);}var O=[];var Q=function(S,T){var R=S;if(T.override){if(T.override===true){R=T.obj;}else{R=T.override;}}T.fn.call(R,T.obj);};var L,K,N,M;for(L=0,K=F.length;L<K;++L){N=F[L];if(N&&!N.checkReady){M=this.getEl(N.id);if(M){Q(M,N);F[L]=null;}else{O.push(N);}}}for(L=0,K=F.length;L<K;++L){N=F[L];if(N&&N.checkReady){M=this.getEl(N.id);if(M){if(H||M.nextSibling){Q(M,N);F[L]=null;}}else{O.push(N);}}}C=(O.length===0)?0:C-1;if(P){this.startInterval();}else{clearInterval(this._interval);this._interval=null;}this.locked=false;return true;},purgeElement:function(O,P,R){var M=(YAHOO.lang.isString(O))?this.getEl(O):O;var Q=this.getListeners(M,R),N,K;if(Q){for(N=0,K=Q.length;N<K;++N){var L=Q[N];this.removeListener(M,L.type,L.fn,L.index);}}if(P&&M&&M.childNodes){for(N=0,K=M.childNodes.length;N<K;++N){this.purgeElement(M.childNodes[N],P,R);}}},getListeners:function(M,K){var P=[],L;if(!K){L=[I,J];}else{if(K==="unload"){L=[J];}else{L=[I];}}var R=(YAHOO.lang.isString(M))?this.getEl(M):M;for(var O=0;O<L.length;O=O+1){var T=L[O];if(T&&T.length>0){for(var Q=0,S=T.length;Q<S;++Q){var N=T[Q];if(N&&N[this.EL]===R&&(!K||K===N[this.TYPE])){P.push({type:N[this.TYPE],fn:N[this.FN],obj:N[this.OBJ],adjust:N[this.OVERRIDE],scope:N[this.ADJ_SCOPE],index:Q});}}}}return(P.length)?P:null;},_unload:function(R){var Q=YAHOO.util.Event,O,N,L,K,M;for(O=0,K=J.length;O<K;++O){L=J[O];if(L){var P=window;if(L[Q.ADJ_SCOPE]){if(L[Q.ADJ_SCOPE]===true){P=L[Q.UNLOAD_OBJ];}else{P=L[Q.ADJ_SCOPE];}}L[Q.FN].call(P,Q.getEvent(R,L[Q.EL]),L[Q.UNLOAD_OBJ]);J[O]=null;L=null;P=null;}}J=null;if(YAHOO.env.ua.IE&&I&&I.length>0){N=I.length;while(N){M=N-1;L=I[M];if(L){L[Q.EL].clearAttributes();}N=N-1;}L=null;}G=null;Q._simpleRemove(window,"unload",Q._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var K=document.documentElement,L=document.body;if(K&&(K.scrollTop||K.scrollLeft)){return[K.scrollTop,K.scrollLeft];}else{if(L){return[L.scrollTop,L.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(M,N,L,K){M.addEventListener(N,L,(K));};}else{if(window.attachEvent){return function(M,N,L,K){M.attachEvent("on"+N,L);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(M,N,L,K){M.removeEventListener(N,L,(K));};}else{if(window.detachEvent){return function(L,M,K){L.detachEvent("on"+M,K);};}else{return function(){};}}}()};}();(function(){var A=YAHOO.util.Event;A.on=A.addListener;if(A.isIE){YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);A._dri=setInterval(function(){var C=document.createElement("p");try{C.doScroll("left");clearInterval(A._dri);A._dri=null;A._ready();C=null;}catch(B){C=null;}},A.POLL_INTERVAL);}else{if(A.webkit){A._dri=setInterval(function(){var B=document.readyState;if("loaded"==B||"complete"==B){clearInterval(A._dri);A._dri=null;A._ready();}},A.POLL_INTERVAL);}else{A._simpleAdd(document,"DOMContentLoaded",A._ready);}}A._simpleAdd(window,"load",A._load);A._simpleAdd(window,"unload",A._unload);A._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{};var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,override:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A);},createEvent:function(G,D){this.__yui_events=this.__yui_events||{};var A=D||{};var I=this.__yui_events;if(I[G]){}else{var H=A.scope||this;var E=(A.silent);var B=new YAHOO.util.CustomEvent(G,H,E,YAHOO.util.CustomEvent.FLAT);I[G]=B;if(A.onSubscribeCallback){B.subscribeEvent.subscribe(A.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};
var F=this.__yui_subscribers[G];if(F){for(var C=0;C<F.length;++C){B.subscribe(F[C].fn,F[C].obj,F[C].override);}}}return I[G];},fireEvent:function(E,D,A,C){this.__yui_events=this.__yui_events||{};var G=this.__yui_events[E];if(!G){return null;}var B=[];for(var F=1;F<arguments.length;++F){B.push(arguments[F]);}return G.fire.apply(G,B);},hasEvent:function(A){if(this.__yui_events){if(this.__yui_events[A]){return true;}}return false;}};YAHOO.util.KeyListener=function(A,F,B,C){if(!A){}else{if(!F){}else{if(!B){}}}if(!C){C=YAHOO.util.KeyListener.KEYDOWN;}var D=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(typeof A=="string"){A=document.getElementById(A);}if(typeof B=="function"){D.subscribe(B);}else{D.subscribe(B.fn,B.scope,B.correctScope);}function E(J,I){if(!F.shift){F.shift=false;}if(!F.alt){F.alt=false;}if(!F.ctrl){F.ctrl=false;}if(J.shiftKey==F.shift&&J.altKey==F.alt&&J.ctrlKey==F.ctrl){var G;if(F.keys instanceof Array){for(var H=0;H<F.keys.length;H++){G=F.keys[H];if(G==J.charCode){D.fire(J.charCode,J);break;}else{if(G==J.keyCode){D.fire(J.keyCode,J);break;}}}}else{G=F.keys;if(G==J.charCode){D.fire(J.charCode,J);}else{if(G==J.keyCode){D.fire(J.keyCode,J);}}}}}this.enable=function(){if(!this.enabled){YAHOO.util.Event.addListener(A,C,E);this.enabledEvent.fire(F);}this.enabled=true;};this.disable=function(){if(this.enabled){YAHOO.util.Event.removeListener(A,C,E);this.disabledEvent.fire(F);}this.enabled=false;};this.toString=function(){return"KeyListener ["+F.keys+"] "+A.tagName+(A.id?"["+A.id+"]":"");};};YAHOO.util.KeyListener.KEYDOWN="keydown";YAHOO.util.KeyListener.KEYUP="keyup";YAHOO.util.KeyListener.KEY={ALT:18,BACK_SPACE:8,CAPS_LOCK:20,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,META:224,NUM_LOCK:144,PAGE_DOWN:34,PAGE_UP:33,PAUSE:19,PRINTSCREEN:44,RIGHT:39,SCROLL_LOCK:145,SHIFT:16,SPACE:32,TAB:9,UP:38};YAHOO.register("event",YAHOO.util.Event,{version:"2.4.0",build:"733"});YAHOO.register("yahoo-dom-event", YAHOO, {version: "2.4.0", build: "733"});
/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.4.0
*/
YAHOO.util.Get=function(){var I={},H=0,B=0,O=false,A=YAHOO.env.ua,D=YAHOO.lang;var Q=function(U,R,V){var S=V||window,W=S.document,X=W.createElement(U);for(var T in R){if(R[T]&&YAHOO.lang.hasOwnProperty(R,T)){X.setAttribute(T,R[T]);}}return X;};var N=function(R,S){return Q("link",{"id":"yui__dyn_"+(B++),"type":"text/css","rel":"stylesheet","href":R},S);};var M=function(R,S){return Q("script",{"id":"yui__dyn_"+(B++),"type":"text/javascript","src":R},S);};var K=function(R){return{tId:R.tId,win:R.win,data:R.data,nodes:R.nodes,purge:function(){J(this.tId);}};};var P=function(T){var R=I[T];if(R.onFailure){var S=R.scope||R.win;R.onFailure.call(S,K(R));}};var F=function(T){var R=I[T];R.finished=true;if(R.aborted){P(T);return ;}if(R.onSuccess){var S=R.scope||R.win;R.onSuccess.call(S,K(R));}};var E=function(T,W){var S=I[T];if(S.aborted){P(T);return ;}if(W){S.url.shift();if(S.varName){S.varName.shift();}}else{S.url=(D.isString(S.url))?[S.url]:S.url;if(S.varName){S.varName=(D.isString(S.varName))?[S.varName]:S.varName;}}var Z=S.win,Y=Z.document,X=Y.getElementsByTagName("head")[0],U;if(S.url.length===0){if(S.type==="script"&&A.webkit&&A.webkit<420&&!S.finalpass&&!S.varName){var V=M(null,S.win);V.innerHTML="YAHOO.util.Get._finalize(\""+T+"\");";S.nodes.push(V);X.appendChild(V);}else{F(T);}return ;}var R=S.url[0];if(S.type==="script"){U=M(R,Z);}else{U=N(R,Z);}G(S.type,U,T,R,Z,S.url.length);S.nodes.push(U);X.appendChild(U);if((A.webkit||A.gecko)&&S.type==="css"){E(T,R);}};var C=function(){if(O){return ;}O=true;for(var R in I){var S=I[R];if(S.autopurge&&S.finished){J(S.tId);}}O=false;};var J=function(X){var U=I[X];if(U){var W=U.nodes,R=W.length,V=U.win.document,T=V.getElementsByTagName("head")[0];for(var S=0;S<R;S=S+1){T.removeChild(W[S]);}}};var L=function(S,R,T){var V="q"+(H++);T=T||{};if(H%YAHOO.util.Get.PURGE_THRESH===0){C();}I[V]=D.merge(T,{tId:V,type:S,url:R,finished:false,nodes:[]});var U=I[V];U.win=U.win||window;U.scope=U.scope||U.win;U.autopurge=("autopurge" in U)?U.autopurge:(S==="script")?true:false;D.later(0,U,E,V);return{tId:V};};var G=function(a,V,U,S,W,X,Z){var Y=Z||E;if(A.ie){V.onreadystatechange=function(){var b=this.readyState;if("loaded"===b||"complete"===b){Y(U,S);}};}else{if(A.webkit){if(a==="script"){if(A.webkit>419){V.addEventListener("load",function(){Y(U,S);});}else{var R=I[U];if(R.varName){var T=YAHOO.util.Get.POLL_FREQ;R.maxattempts=YAHOO.util.Get.TIMEOUT/T;R.attempts=0;R._cache=R.varName[0].split(".");R.timer=D.later(T,R,function(f){var d=this._cache,c=d.length,b=this.win,e;for(e=0;e<c;e=e+1){b=b[d[e]];if(!b){this.attempts++;if(this.attempts++>this.maxattempts){R.timer.cancel();P(U);}else{}return ;}}R.timer.cancel();Y(U,S);},null,true);}else{D.later(YAHOO.util.Get.POLL_FREQ,null,Y,[U,S]);}}}}else{V.onload=function(){Y(U,S);};}}};return{POLL_FREQ:10,PURGE_THRESH:20,TIMEOUT:2000,_finalize:function(R){D.later(0,null,F,R);},abort:function(S){var T=(D.isString(S))?S:S.tId;var R=I[T];if(R){R.aborted=true;}},script:function(R,S){return L("script",R,S);},css:function(R,S){return L("css",R,S);}};}();YAHOO.register("get",YAHOO.util.Get,{version:"2.4.0",build:"733"});/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.4.0
*/
YAHOO.widget.AutoComplete=function(G,B,J,D){if(G&&B&&J){if(J instanceof YAHOO.widget.DataSource){this.dataSource=J;}else{return ;}if(YAHOO.util.Dom.inDocument(G)){if(YAHOO.lang.isString(G)){this._sName="instance"+YAHOO.widget.AutoComplete._nIndex+" "+G;this._oTextbox=document.getElementById(G);}else{this._sName=(G.id)?"instance"+YAHOO.widget.AutoComplete._nIndex+" "+G.id:"instance"+YAHOO.widget.AutoComplete._nIndex;this._oTextbox=G;}YAHOO.util.Dom.addClass(this._oTextbox,"yui-ac-input");}else{return ;}if(YAHOO.util.Dom.inDocument(B)){if(YAHOO.lang.isString(B)){this._oContainer=document.getElementById(B);}else{this._oContainer=B;}if(this._oContainer.style.display=="none"){}var E=this._oContainer.parentNode;var A=E.tagName.toLowerCase();if(A=="div"){YAHOO.util.Dom.addClass(E,"yui-ac");}else{}}else{return ;}if(D&&(D.constructor==Object)){for(var I in D){if(I){this[I]=D[I];}}}this._initContainer();this._initProps();this._initList();this._initContainerHelpers();var H=this;var F=this._oTextbox;var C=this._oContainer._oContent;YAHOO.util.Event.addListener(F,"keyup",H._onTextboxKeyUp,H);YAHOO.util.Event.addListener(F,"keydown",H._onTextboxKeyDown,H);YAHOO.util.Event.addListener(F,"focus",H._onTextboxFocus,H);YAHOO.util.Event.addListener(F,"blur",H._onTextboxBlur,H);YAHOO.util.Event.addListener(C,"mouseover",H._onContainerMouseover,H);YAHOO.util.Event.addListener(C,"mouseout",H._onContainerMouseout,H);YAHOO.util.Event.addListener(C,"scroll",H._onContainerScroll,H);YAHOO.util.Event.addListener(C,"resize",H._onContainerResize,H);YAHOO.util.Event.addListener(F,"keypress",H._onTextboxKeyPress,H);YAHOO.util.Event.addListener(window,"unload",H._onWindowUnload,H);this.textboxFocusEvent=new YAHOO.util.CustomEvent("textboxFocus",this);this.textboxKeyEvent=new YAHOO.util.CustomEvent("textboxKey",this);this.dataRequestEvent=new YAHOO.util.CustomEvent("dataRequest",this);this.dataReturnEvent=new YAHOO.util.CustomEvent("dataReturn",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.containerExpandEvent=new YAHOO.util.CustomEvent("containerExpand",this);this.typeAheadEvent=new YAHOO.util.CustomEvent("typeAhead",this);this.itemMouseOverEvent=new YAHOO.util.CustomEvent("itemMouseOver",this);this.itemMouseOutEvent=new YAHOO.util.CustomEvent("itemMouseOut",this);this.itemArrowToEvent=new YAHOO.util.CustomEvent("itemArrowTo",this);this.itemArrowFromEvent=new YAHOO.util.CustomEvent("itemArrowFrom",this);this.itemSelectEvent=new YAHOO.util.CustomEvent("itemSelect",this);this.unmatchedItemSelectEvent=new YAHOO.util.CustomEvent("unmatchedItemSelect",this);this.selectionEnforceEvent=new YAHOO.util.CustomEvent("selectionEnforce",this);this.containerCollapseEvent=new YAHOO.util.CustomEvent("containerCollapse",this);this.textboxBlurEvent=new YAHOO.util.CustomEvent("textboxBlur",this);F.setAttribute("autocomplete","off");YAHOO.widget.AutoComplete._nIndex++;}else{}};YAHOO.widget.AutoComplete.prototype.dataSource=null;YAHOO.widget.AutoComplete.prototype.minQueryLength=1;YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed=10;YAHOO.widget.AutoComplete.prototype.queryDelay=0.2;YAHOO.widget.AutoComplete.prototype.highlightClassName="yui-ac-highlight";YAHOO.widget.AutoComplete.prototype.prehighlightClassName=null;YAHOO.widget.AutoComplete.prototype.delimChar=null;YAHOO.widget.AutoComplete.prototype.autoHighlight=true;YAHOO.widget.AutoComplete.prototype.typeAhead=false;YAHOO.widget.AutoComplete.prototype.animHoriz=false;YAHOO.widget.AutoComplete.prototype.animVert=true;YAHOO.widget.AutoComplete.prototype.animSpeed=0.3;YAHOO.widget.AutoComplete.prototype.forceSelection=false;YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete=true;YAHOO.widget.AutoComplete.prototype.alwaysShowContainer=false;YAHOO.widget.AutoComplete.prototype.useIFrame=false;YAHOO.widget.AutoComplete.prototype.useShadow=false;YAHOO.widget.AutoComplete.prototype.toString=function(){return"AutoComplete "+this._sName;};YAHOO.widget.AutoComplete.prototype.isContainerOpen=function(){return this._bContainerOpen;};YAHOO.widget.AutoComplete.prototype.getListItems=function(){return this._aListItems;};YAHOO.widget.AutoComplete.prototype.getListItemData=function(A){if(A._oResultData){return A._oResultData;}else{return false;}};YAHOO.widget.AutoComplete.prototype.setHeader=function(A){if(A){if(this._oContainer._oContent._oHeader){this._oContainer._oContent._oHeader.innerHTML=A;this._oContainer._oContent._oHeader.style.display="block";}}else{this._oContainer._oContent._oHeader.innerHTML="";this._oContainer._oContent._oHeader.style.display="none";}};YAHOO.widget.AutoComplete.prototype.setFooter=function(A){if(A){if(this._oContainer._oContent._oFooter){this._oContainer._oContent._oFooter.innerHTML=A;this._oContainer._oContent._oFooter.style.display="block";}}else{this._oContainer._oContent._oFooter.innerHTML="";this._oContainer._oContent._oFooter.style.display="none";}};YAHOO.widget.AutoComplete.prototype.setBody=function(A){if(A){if(this._oContainer._oContent._oBody){this._oContainer._oContent._oBody.innerHTML=A;this._oContainer._oContent._oBody.style.display="block";this._oContainer._oContent.style.display="block";}}else{this._oContainer._oContent._oBody.innerHTML="";this._oContainer._oContent.style.display="none";}this._maxResultsDisplayed=0;};YAHOO.widget.AutoComplete.prototype.formatResult=function(B,C){var A=B[0];if(A){return A;}else{return"";}};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(A,B,D,C){return true;};YAHOO.widget.AutoComplete.prototype.sendQuery=function(A){this._sendQuery(A);};YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery=function(A){return A;};YAHOO.widget.AutoComplete.prototype.destroy=function(){var B=this.toString();var A=this._oTextbox;var D=this._oContainer;this.textboxFocusEvent.unsubscribe();this.textboxKeyEvent.unsubscribe();this.dataRequestEvent.unsubscribe();this.dataReturnEvent.unsubscribe();this.dataErrorEvent.unsubscribe();this.containerExpandEvent.unsubscribe();this.typeAheadEvent.unsubscribe();
this.itemMouseOverEvent.unsubscribe();this.itemMouseOutEvent.unsubscribe();this.itemArrowToEvent.unsubscribe();this.itemArrowFromEvent.unsubscribe();this.itemSelectEvent.unsubscribe();this.unmatchedItemSelectEvent.unsubscribe();this.selectionEnforceEvent.unsubscribe();this.containerCollapseEvent.unsubscribe();this.textboxBlurEvent.unsubscribe();YAHOO.util.Event.purgeElement(A,true);YAHOO.util.Event.purgeElement(D,true);D.innerHTML="";for(var C in this){if(YAHOO.lang.hasOwnProperty(this,C)){this[C]=null;}}};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;YAHOO.widget.AutoComplete._nIndex=0;YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._oTextbox=null;YAHOO.widget.AutoComplete.prototype._bFocused=true;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._oContainer=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._aListItems=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._maxResultsDisplayed=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sSavedQuery=null;YAHOO.widget.AutoComplete.prototype._oCurItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var B=this.minQueryLength;if(!YAHOO.lang.isNumber(B)){this.minQueryLength=1;}var D=this.maxResultsDisplayed;if(!YAHOO.lang.isNumber(D)||(D<1)){this.maxResultsDisplayed=10;}var E=this.queryDelay;if(!YAHOO.lang.isNumber(E)||(E<0)){this.queryDelay=0.2;}var A=this.delimChar;if(YAHOO.lang.isString(A)&&(A.length>0)){this.delimChar=[A];}else{if(!YAHOO.lang.isArray(A)){this.delimChar=null;}}var C=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(!YAHOO.lang.isNumber(C)||(C<0)){this.animSpeed=0.3;}if(!this._oAnim){this._oAnim=new YAHOO.util.Anim(this._oContainer._oContent,{},this.animSpeed);}else{this._oAnim.duration=this.animSpeed;}}if(this.forceSelection&&A){}};YAHOO.widget.AutoComplete.prototype._initContainerHelpers=function(){if(this.useShadow&&!this._oContainer._oShadow){var B=document.createElement("div");B.className="yui-ac-shadow";this._oContainer._oShadow=this._oContainer.appendChild(B);}if(this.useIFrame&&!this._oContainer._oIFrame){var A=document.createElement("iframe");A.src=this._iFrameSrc;A.frameBorder=0;A.scrolling="no";A.style.position="absolute";A.style.width="100%";A.style.height="100%";A.tabIndex=-1;this._oContainer._oIFrame=this._oContainer.appendChild(A);}};YAHOO.widget.AutoComplete.prototype._initContainer=function(){YAHOO.util.Dom.addClass(this._oContainer,"yui-ac-container");if(!this._oContainer._oContent){var D=document.createElement("div");D.className="yui-ac-content";D.style.display="none";this._oContainer._oContent=this._oContainer.appendChild(D);var B=document.createElement("div");B.className="yui-ac-hd";B.style.display="none";this._oContainer._oContent._oHeader=this._oContainer._oContent.appendChild(B);var C=document.createElement("div");C.className="yui-ac-bd";this._oContainer._oContent._oBody=this._oContainer._oContent.appendChild(C);var A=document.createElement("div");A.className="yui-ac-ft";A.style.display="none";this._oContainer._oContent._oFooter=this._oContainer._oContent.appendChild(A);}else{}};YAHOO.widget.AutoComplete.prototype._initList=function(){this._aListItems=[];while(this._oContainer._oContent._oBody.hasChildNodes()){var B=this.getListItems();if(B){for(var A=B.length-1;A>=0;A--){B[A]=null;}}this._oContainer._oContent._oBody.innerHTML="";}var E=document.createElement("ul");E=this._oContainer._oContent._oBody.appendChild(E);for(var C=0;C<this.maxResultsDisplayed;C++){var D=document.createElement("li");D=E.appendChild(D);this._aListItems[C]=D;this._initListItem(D,C);}this._maxResultsDisplayed=this.maxResultsDisplayed;};YAHOO.widget.AutoComplete.prototype._initListItem=function(C,B){var A=this;C.style.display="none";C._nItemIndex=B;C.mouseover=C.mouseout=C.onclick=null;YAHOO.util.Event.addListener(C,"mouseover",A._onItemMouseover,A);YAHOO.util.Event.addListener(C,"mouseout",A._onItemMouseout,A);YAHOO.util.Event.addListener(C,"click",A._onItemMouseclick,A);};YAHOO.widget.AutoComplete.prototype._onIMEDetected=function(A){A._enableIntervalDetection();};YAHOO.widget.AutoComplete.prototype._enableIntervalDetection=function(){var A=this._oTextbox.value;var B=this._sLastTextboxValue;if(A!=B){this._sLastTextboxValue=A;this._sendQuery(A);}};YAHOO.widget.AutoComplete.prototype._cancelIntervalDetection=function(A){if(A._queryInterval){clearInterval(A._queryInterval);}};YAHOO.widget.AutoComplete.prototype._isIgnoreKey=function(A){if((A==9)||(A==13)||(A==16)||(A==17)||(A>=18&&A<=20)||(A==27)||(A>=33&&A<=35)||(A>=36&&A<=40)||(A>=44&&A<=45)){return true;
}return false;};YAHOO.widget.AutoComplete.prototype._sendQuery=function(G){if(this.minQueryLength==-1){this._toggleContainer(false);return ;}var C=(this.delimChar)?this.delimChar:null;if(C){var E=-1;for(var B=C.length-1;B>=0;B--){var F=G.lastIndexOf(C[B]);if(F>E){E=F;}}if(C[B]==" "){for(var A=C.length-1;A>=0;A--){if(G[E-1]==C[A]){E--;break;}}}if(E>-1){var D=E+1;while(G.charAt(D)==" "){D+=1;}this._sSavedQuery=G.substring(0,D);G=G.substr(D);}else{if(G.indexOf(this._sSavedQuery)<0){this._sSavedQuery=null;}}}if((G&&(G.length<this.minQueryLength))||(!G&&this.minQueryLength>0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID);}this._toggleContainer(false);return ;}G=encodeURIComponent(G);this._nDelayID=-1;G=this.doBeforeSendQuery(G);this.dataRequestEvent.fire(this,G);this.dataSource.getResults(this._populateList,G,this);};YAHOO.widget.AutoComplete.prototype._populateList=function(K,L,I){if(L===null){I.dataErrorEvent.fire(I,K);}if(!I._bFocused||!L){return ;}var A=(navigator.userAgent.toLowerCase().indexOf("opera")!=-1);var O=I._oContainer._oContent.style;O.width=(!A)?null:"";O.height=(!A)?null:"";var H=decodeURIComponent(K);I._sCurQuery=H;I._bItemSelected=false;if(I._maxResultsDisplayed!=I.maxResultsDisplayed){I._initList();}var C=Math.min(L.length,I.maxResultsDisplayed);I._nDisplayedItems=C;if(C>0){I._initContainerHelpers();var D=I._aListItems;for(var G=C-1;G>=0;G--){var N=D[G];var B=L[G];N.innerHTML=I.formatResult(B,H);N.style.display="list-item";N._sResultKey=B[0];N._oResultData=B;}for(var F=D.length-1;F>=C;F--){var M=D[F];M.innerHTML=null;M.style.display="none";M._sResultKey=null;M._oResultData=null;}var J=I.doBeforeExpandContainer(I._oTextbox,I._oContainer,K,L);I._toggleContainer(J);if(I.autoHighlight){var E=D[0];I._toggleHighlight(E,"to");I.itemArrowToEvent.fire(I,E);I._typeAhead(E,K);}else{I._oCurItem=null;}}else{I._toggleContainer(false);}I.dataReturnEvent.fire(I,K,L);};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var C=this._oTextbox.value;var B=(this.delimChar)?this.delimChar[0]:null;var A=(B)?C.lastIndexOf(B,C.length-2):-1;if(A>-1){this._oTextbox.value=C.substring(0,A);}else{this._oTextbox.value="";}this._sSavedQuery=this._oTextbox.value;this.selectionEnforceEvent.fire(this);};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var D=null;for(var A=this._nDisplayedItems-1;A>=0;A--){var C=this._aListItems[A];var B=C._sResultKey.toLowerCase();if(B==this._sCurQuery.toLowerCase()){D=C;break;}}return(D);};YAHOO.widget.AutoComplete.prototype._typeAhead=function(E,G){if(!this.typeAhead||(this._nKeyCode==8)){return ;}var B=this._oTextbox;var F=this._oTextbox.value;if(!B.setSelectionRange&&!B.createTextRange){return ;}var C=F.length;this._updateValue(E);var D=B.value.length;this._selectText(B,C,D);var A=B.value.substr(C,D);this.typeAheadEvent.fire(this,G,A);};YAHOO.widget.AutoComplete.prototype._selectText=function(A,B,C){if(A.setSelectionRange){A.setSelectionRange(B,C);}else{if(A.createTextRange){var D=A.createTextRange();D.moveStart("character",B);D.moveEnd("character",C-A.value.length);D.select();}else{A.select();}}};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(B){var D=false;var C=this._oContainer._oContent.offsetWidth+"px";var A=this._oContainer._oContent.offsetHeight+"px";if(this.useIFrame&&this._oContainer._oIFrame){D=true;if(B){this._oContainer._oIFrame.style.width=C;this._oContainer._oIFrame.style.height=A;}else{this._oContainer._oIFrame.style.width=0;this._oContainer._oIFrame.style.height=0;}}if(this.useShadow&&this._oContainer._oShadow){D=true;if(B){this._oContainer._oShadow.style.width=C;this._oContainer._oShadow.style.height=A;}else{this._oContainer._oShadow.style.width=0;this._oContainer._oShadow.style.height=0;}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(J){var L=this._oContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return ;}if(!J){this._oContainer._oContent.scrollTop=0;var C=this._aListItems;if(C&&(C.length>0)){for(var G=C.length-1;G>=0;G--){C[G].style.display="none";}}if(this._oCurItem){this._toggleHighlight(this._oCurItem,"from");}this._oCurItem=null;this._nDisplayedItems=0;this._sCurQuery=null;}if(!J&&!this._bContainerOpen){L._oContent.style.display="none";return ;}var B=this._oAnim;if(B&&B.getEl()&&(this.animHoriz||this.animVert)){if(!J){this._toggleContainerHelpers(J);}if(B.isAnimated()){B.stop();}var H=L._oContent.cloneNode(true);L.appendChild(H);H.style.top="-9000px";H.style.display="block";var F=H.offsetWidth;var D=H.offsetHeight;var A=(this.animHoriz)?0:F;var E=(this.animVert)?0:D;B.attributes=(J)?{width:{to:F},height:{to:D}}:{width:{to:A},height:{to:E}};if(J&&!this._bContainerOpen){L._oContent.style.width=A+"px";L._oContent.style.height=E+"px";}else{L._oContent.style.width=F+"px";L._oContent.style.height=D+"px";}L.removeChild(H);H=null;var I=this;var K=function(){B.onComplete.unsubscribeAll();if(J){I.containerExpandEvent.fire(I);}else{L._oContent.style.display="none";I.containerCollapseEvent.fire(I);}I._toggleContainerHelpers(J);};L._oContent.style.display="block";B.onComplete.subscribe(K);B.animate();this._bContainerOpen=J;}else{if(J){L._oContent.style.display="block";this.containerExpandEvent.fire(this);}else{L._oContent.style.display="none";this.containerCollapseEvent.fire(this);}this._toggleContainerHelpers(J);this._bContainerOpen=J;}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(A,C){var B=this.highlightClassName;if(this._oCurItem){YAHOO.util.Dom.removeClass(this._oCurItem,B);}if((C=="to")&&B){YAHOO.util.Dom.addClass(A,B);this._oCurItem=A;}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(A,C){if(A==this._oCurItem){return ;}var B=this.prehighlightClassName;if((C=="mouseover")&&B){YAHOO.util.Dom.addClass(A,B);}else{YAHOO.util.Dom.removeClass(A,B);}};YAHOO.widget.AutoComplete.prototype._updateValue=function(F){var C=this._oTextbox;var E=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var B=this._sSavedQuery;var D=F._sResultKey;C.focus();
C.value="";if(E){if(B){C.value=B;}C.value+=D+E;if(E!=" "){C.value+=" ";}}else{C.value=D;}if(C.type=="textarea"){C.scrollTop=C.scrollHeight;}var A=C.value.length;this._selectText(C,A,A);this._oCurItem=F;};YAHOO.widget.AutoComplete.prototype._selectItem=function(A){this._bItemSelected=true;this._updateValue(A);this._cancelIntervalDetection(this);this.itemSelectEvent.fire(this,A,A._oResultData);this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(this._oCurItem){this._selectItem(this._oCurItem);}else{this._toggleContainer(false);}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(G){if(this._bContainerOpen){var D=this._oCurItem;var F=-1;if(D){F=D._nItemIndex;}var C=(G==40)?(F+1):(F-1);if(C<-2||C>=this._nDisplayedItems){return ;}if(D){this._toggleHighlight(D,"from");this.itemArrowFromEvent.fire(this,D);}if(C==-1){if(this.delimChar&&this._sSavedQuery){if(!this._textMatchesOption()){this._oTextbox.value=this._sSavedQuery;}else{this._oTextbox.value=this._sSavedQuery+this._sCurQuery;}}else{this._oTextbox.value=this._sCurQuery;}this._oCurItem=null;return ;}if(C==-2){this._toggleContainer(false);return ;}var B=this._aListItems[C];var E=this._oContainer._oContent;var A=((YAHOO.util.Dom.getStyle(E,"overflow")=="auto")||(YAHOO.util.Dom.getStyle(E,"overflowY")=="auto"));if(A&&(C>-1)&&(C<this._nDisplayedItems)){if(G==40){if((B.offsetTop+B.offsetHeight)>(E.scrollTop+E.offsetHeight)){E.scrollTop=(B.offsetTop+B.offsetHeight)-E.offsetHeight;}else{if((B.offsetTop+B.offsetHeight)<E.scrollTop){E.scrollTop=B.offsetTop;}}}else{if(B.offsetTop<E.scrollTop){this._oContainer._oContent.scrollTop=B.offsetTop;}else{if(B.offsetTop>(E.scrollTop+E.offsetHeight)){this._oContainer._oContent.scrollTop=(B.offsetTop+B.offsetHeight)-E.offsetHeight;}}}}this._toggleHighlight(B,"to");this.itemArrowToEvent.fire(this,B);if(this.typeAhead){this._updateValue(B);}}};YAHOO.widget.AutoComplete.prototype._onItemMouseover=function(A,B){if(B.prehighlightClassName){B._togglePrehighlight(this,"mouseover");}else{B._toggleHighlight(this,"to");}B.itemMouseOverEvent.fire(B,this);};YAHOO.widget.AutoComplete.prototype._onItemMouseout=function(A,B){if(B.prehighlightClassName){B._togglePrehighlight(this,"mouseout");}else{B._toggleHighlight(this,"from");}B.itemMouseOutEvent.fire(B,this);};YAHOO.widget.AutoComplete.prototype._onItemMouseclick=function(A,B){B._toggleHighlight(this,"to");B._selectItem(this);};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(A,B){B._bOverContainer=true;};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(A,B){B._bOverContainer=false;if(B._oCurItem){B._toggleHighlight(B._oCurItem,"to");}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(A,B){B._oTextbox.focus();};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(A,B){B._toggleContainerHelpers(B._bContainerOpen);};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(A,C){var D=A.keyCode;switch(D){case 9:if(C._oCurItem){if(C.delimChar&&(C._nKeyCode!=D)){if(C._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}C._selectItem(C._oCurItem);}else{C._toggleContainer(false);}break;case 13:var B=(navigator.userAgent.toLowerCase().indexOf("mac")!=-1);if(!B){if(C._oCurItem){if(C._nKeyCode!=D){if(C._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}C._selectItem(C._oCurItem);}else{C._toggleContainer(false);}}break;case 27:C._toggleContainer(false);return ;case 39:C._jumpSelection();break;case 38:YAHOO.util.Event.stopEvent(A);C._moveSelection(D);break;case 40:YAHOO.util.Event.stopEvent(A);C._moveSelection(D);break;default:break;}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(A,C){var D=A.keyCode;var B=(navigator.userAgent.toLowerCase().indexOf("mac")!=-1);if(B){switch(D){case 9:if(C._oCurItem){if(C.delimChar&&(C._nKeyCode!=D)){YAHOO.util.Event.stopEvent(A);}}break;case 13:if(C._oCurItem){if(C._nKeyCode!=D){if(C._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}C._selectItem(C._oCurItem);}else{C._toggleContainer(false);}break;case 38:case 40:YAHOO.util.Event.stopEvent(A);break;default:break;}}else{if(D==229){C._queryInterval=setInterval(function(){C._onIMEDetected(C);},500);}}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(B,D){D._initProps();var E=B.keyCode;D._nKeyCode=E;var C=this.value;if(D._isIgnoreKey(E)||(C.toLowerCase()==D._sCurQuery)){return ;}else{D._bItemSelected=false;YAHOO.util.Dom.removeClass(D._oCurItem,D.highlightClassName);D._oCurItem=null;D.textboxKeyEvent.fire(D,E);}if(D.queryDelay>0){var A=setTimeout(function(){D._sendQuery(C);},(D.queryDelay*1000));if(D._nDelayID!=-1){clearTimeout(D._nDelayID);}D._nDelayID=A;}else{D._sendQuery(C);}};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(A,B){B._oTextbox.setAttribute("autocomplete","off");B._bFocused=true;if(!B._bItemSelected){B.textboxFocusEvent.fire(B);}};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(A,B){if(!B._bOverContainer||(B._nKeyCode==9)){if(!B._bItemSelected){var C=B._textMatchesOption();if(!B._bContainerOpen||(B._bContainerOpen&&(C===null))){if(B.forceSelection){B._clearSelection();}else{B.unmatchedItemSelectEvent.fire(B);}}else{if(B.forceSelection){B._selectItem(C);}}}if(B._bContainerOpen){B._toggleContainer(false);}B._cancelIntervalDetection(B);B._bFocused=false;B.textboxBlurEvent.fire(B);}};YAHOO.widget.AutoComplete.prototype._onWindowUnload=function(A,B){if(B&&B._oTextbox&&B.allowBrowserAutocomplete){B._oTextbox.setAttribute("autocomplete","on");}};YAHOO.widget.DataSource=function(){};YAHOO.widget.DataSource.ERROR_DATANULL="Response data was null";YAHOO.widget.DataSource.ERROR_DATAPARSE="Response data could not be parsed";YAHOO.widget.DataSource.prototype.maxCacheEntries=15;YAHOO.widget.DataSource.prototype.queryMatchContains=false;YAHOO.widget.DataSource.prototype.queryMatchSubset=false;YAHOO.widget.DataSource.prototype.queryMatchCase=false;YAHOO.widget.DataSource.prototype.toString=function(){return"DataSource "+this._sName;};YAHOO.widget.DataSource.prototype.getResults=function(A,D,B){var C=this._doQueryCache(A,D,B);
if(C.length===0){this.queryEvent.fire(this,B,D);this.doQuery(A,D,B);}};YAHOO.widget.DataSource.prototype.doQuery=function(A,C,B){};YAHOO.widget.DataSource.prototype.flushCache=function(){if(this._aCache){this._aCache=[];}if(this._aCacheHelper){this._aCacheHelper=[];}this.cacheFlushEvent.fire(this);};YAHOO.widget.DataSource.prototype.queryEvent=null;YAHOO.widget.DataSource.prototype.cacheQueryEvent=null;YAHOO.widget.DataSource.prototype.getResultsEvent=null;YAHOO.widget.DataSource.prototype.getCachedResultsEvent=null;YAHOO.widget.DataSource.prototype.dataErrorEvent=null;YAHOO.widget.DataSource.prototype.cacheFlushEvent=null;YAHOO.widget.DataSource._nIndex=0;YAHOO.widget.DataSource.prototype._sName=null;YAHOO.widget.DataSource.prototype._aCache=null;YAHOO.widget.DataSource.prototype._init=function(){var A=this.maxCacheEntries;if(!YAHOO.lang.isNumber(A)||(A<0)){A=0;}if(A>0&&!this._aCache){this._aCache=[];}this._sName="instance"+YAHOO.widget.DataSource._nIndex;YAHOO.widget.DataSource._nIndex++;this.queryEvent=new YAHOO.util.CustomEvent("query",this);this.cacheQueryEvent=new YAHOO.util.CustomEvent("cacheQuery",this);this.getResultsEvent=new YAHOO.util.CustomEvent("getResults",this);this.getCachedResultsEvent=new YAHOO.util.CustomEvent("getCachedResults",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.cacheFlushEvent=new YAHOO.util.CustomEvent("cacheFlush",this);};YAHOO.widget.DataSource.prototype._addCacheElem=function(B){var A=this._aCache;if(!A||!B||!B.query||!B.results){return ;}if(A.length>=this.maxCacheEntries){A.shift();}A.push(B);};YAHOO.widget.DataSource.prototype._doQueryCache=function(A,I,N){var H=[];var G=false;var J=this._aCache;var F=(J)?J.length:0;var K=this.queryMatchContains;var D;if((this.maxCacheEntries>0)&&J&&(F>0)){this.cacheQueryEvent.fire(this,N,I);if(!this.queryMatchCase){D=I;I=I.toLowerCase();}for(var P=F-1;P>=0;P--){var E=J[P];var B=E.results;var C=(!this.queryMatchCase)?encodeURIComponent(E.query).toLowerCase():encodeURIComponent(E.query);if(C==I){G=true;H=B;if(P!=F-1){J.splice(P,1);this._addCacheElem(E);}break;}else{if(this.queryMatchSubset){for(var O=I.length-1;O>=0;O--){var R=I.substr(0,O);if(C==R){G=true;for(var M=B.length-1;M>=0;M--){var Q=B[M];var L=(this.queryMatchCase)?encodeURIComponent(Q[0]).indexOf(I):encodeURIComponent(Q[0]).toLowerCase().indexOf(I);if((!K&&(L===0))||(K&&(L>-1))){H.unshift(Q);}}E={};E.query=I;E.results=H;this._addCacheElem(E);break;}}if(G){break;}}}}if(G){this.getCachedResultsEvent.fire(this,N,D,H);A(D,H,N);}}return H;};YAHOO.widget.DS_XHR=function(C,A,D){if(D&&(D.constructor==Object)){for(var B in D){this[B]=D[B];}}if(!YAHOO.lang.isArray(A)||!YAHOO.lang.isString(C)){return ;}this.schema=A;this.scriptURI=C;this._init();};YAHOO.widget.DS_XHR.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_XHR.TYPE_JSON=0;YAHOO.widget.DS_XHR.TYPE_XML=1;YAHOO.widget.DS_XHR.TYPE_FLAT=2;YAHOO.widget.DS_XHR.ERROR_DATAXHR="XHR response failed";YAHOO.widget.DS_XHR.prototype.connMgr=YAHOO.util.Connect;YAHOO.widget.DS_XHR.prototype.connTimeout=0;YAHOO.widget.DS_XHR.prototype.scriptURI=null;YAHOO.widget.DS_XHR.prototype.scriptQueryParam="query";YAHOO.widget.DS_XHR.prototype.scriptQueryAppend="";YAHOO.widget.DS_XHR.prototype.responseType=YAHOO.widget.DS_XHR.TYPE_JSON;YAHOO.widget.DS_XHR.prototype.responseStripAfter="\n<!-";YAHOO.widget.DS_XHR.prototype.doQuery=function(E,G,B){var J=(this.responseType==YAHOO.widget.DS_XHR.TYPE_XML);var D=this.scriptURI+"?"+this.scriptQueryParam+"="+G;if(this.scriptQueryAppend.length>0){D+="&"+this.scriptQueryAppend;}var C=null;var F=this;var I=function(K){if(!F._oConn||(K.tId!=F._oConn.tId)){F.dataErrorEvent.fire(F,B,G,YAHOO.widget.DataSource.ERROR_DATANULL);return ;}for(var N in K){}if(!J){K=K.responseText;}else{K=K.responseXML;}if(K===null){F.dataErrorEvent.fire(F,B,G,YAHOO.widget.DataSource.ERROR_DATANULL);return ;}var M=F.parseResponse(G,K,B);var L={};L.query=decodeURIComponent(G);L.results=M;if(M===null){F.dataErrorEvent.fire(F,B,G,YAHOO.widget.DataSource.ERROR_DATAPARSE);M=[];}else{F.getResultsEvent.fire(F,B,G,M);F._addCacheElem(L);}E(G,M,B);};var A=function(K){F.dataErrorEvent.fire(F,B,G,YAHOO.widget.DS_XHR.ERROR_DATAXHR);return ;};var H={success:I,failure:A};if(YAHOO.lang.isNumber(this.connTimeout)&&(this.connTimeout>0)){H.timeout=this.connTimeout;}if(this._oConn){this.connMgr.abort(this._oConn);}F._oConn=this.connMgr.asyncRequest("GET",D,H,null);};YAHOO.widget.DS_XHR.prototype.parseResponse=function(sQuery,oResponse,oParent){var aSchema=this.schema;var aResults=[];var bError=false;var nEnd=((this.responseStripAfter!=="")&&(oResponse.indexOf))?oResponse.indexOf(this.responseStripAfter):-1;if(nEnd!=-1){oResponse=oResponse.substring(0,nEnd);}switch(this.responseType){case YAHOO.widget.DS_XHR.TYPE_JSON:var jsonList,jsonObjParsed;var isNotMac=(navigator.userAgent.toLowerCase().indexOf("khtml")==-1);if(oResponse.parseJSON&&isNotMac){jsonObjParsed=oResponse.parseJSON();if(!jsonObjParsed){bError=true;}else{try{jsonList=eval("jsonObjParsed."+aSchema[0]);}catch(e){bError=true;break;}}}else{if(YAHOO.lang.JSON&&isNotMac){jsonObjParsed=YAHOO.lang.JSON.parse(oResponse);if(!jsonObjParsed){bError=true;break;}else{try{jsonList=eval("jsonObjParsed."+aSchema[0]);}catch(e){bError=true;break;}}}else{if(window.JSON&&isNotMac){jsonObjParsed=JSON.parse(oResponse);if(!jsonObjParsed){bError=true;break;}else{try{jsonList=eval("jsonObjParsed."+aSchema[0]);}catch(e){bError=true;break;}}}else{try{while(oResponse.substring(0,1)==" "){oResponse=oResponse.substring(1,oResponse.length);}if(oResponse.indexOf("{")<0){bError=true;break;}if(oResponse.indexOf("{}")===0){break;}var jsonObjRaw=eval("("+oResponse+")");if(!jsonObjRaw){bError=true;break;}jsonList=eval("(jsonObjRaw."+aSchema[0]+")");}catch(e){bError=true;break;}}}}if(!jsonList){bError=true;break;}if(!YAHOO.lang.isArray(jsonList)){jsonList=[jsonList];}for(var i=jsonList.length-1;i>=0;i--){var aResultItem=[];var jsonResult=jsonList[i];for(var j=aSchema.length-1;j>=1;j--){var dataFieldValue=jsonResult[aSchema[j]];
if(!dataFieldValue){dataFieldValue="";}aResultItem.unshift(dataFieldValue);}if(aResultItem.length==1){aResultItem.push(jsonResult);}aResults.unshift(aResultItem);}break;case YAHOO.widget.DS_XHR.TYPE_XML:var xmlList=oResponse.getElementsByTagName(aSchema[0]);if(!xmlList){bError=true;break;}for(var k=xmlList.length-1;k>=0;k--){var result=xmlList.item(k);var aFieldSet=[];for(var m=aSchema.length-1;m>=1;m--){var sValue=null;var xmlAttr=result.attributes.getNamedItem(aSchema[m]);if(xmlAttr){sValue=xmlAttr.value;}else{var xmlNode=result.getElementsByTagName(aSchema[m]);if(xmlNode&&xmlNode.item(0)&&xmlNode.item(0).firstChild){sValue=xmlNode.item(0).firstChild.nodeValue;}else{sValue="";}}aFieldSet.unshift(sValue);}aResults.unshift(aFieldSet);}break;case YAHOO.widget.DS_XHR.TYPE_FLAT:if(oResponse.length>0){var newLength=oResponse.length-aSchema[0].length;if(oResponse.substr(newLength)==aSchema[0]){oResponse=oResponse.substr(0,newLength);}var aRecords=oResponse.split(aSchema[0]);for(var n=aRecords.length-1;n>=0;n--){aResults[n]=aRecords[n].split(aSchema[1]);}}break;default:break;}sQuery=null;oResponse=null;oParent=null;if(bError){return null;}else{return aResults;}};YAHOO.widget.DS_XHR.prototype._oConn=null;YAHOO.widget.DS_ScriptNode=function(D,A,C){if(C&&(C.constructor==Object)){for(var B in C){this[B]=C[B];}}if(!YAHOO.lang.isArray(A)||!YAHOO.lang.isString(D)){return ;}this.schema=A;this.scriptURI=D;this._init();};YAHOO.widget.DS_ScriptNode.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_ScriptNode.prototype.getUtility=YAHOO.util.Get;YAHOO.widget.DS_ScriptNode.prototype.scriptURI=null;YAHOO.widget.DS_ScriptNode.prototype.scriptQueryParam="query";YAHOO.widget.DS_ScriptNode.prototype.asyncMode="allowAll";YAHOO.widget.DS_ScriptNode.prototype.scriptCallbackParam="callback";YAHOO.widget.DS_ScriptNode.callbacks=[];YAHOO.widget.DS_ScriptNode._nId=0;YAHOO.widget.DS_ScriptNode._nPending=0;YAHOO.widget.DS_ScriptNode.prototype.doQuery=function(A,F,C){var B=this;if(YAHOO.widget.DS_ScriptNode._nPending===0){YAHOO.widget.DS_ScriptNode.callbacks=[];YAHOO.widget.DS_ScriptNode._nId=0;}var E=YAHOO.widget.DS_ScriptNode._nId;YAHOO.widget.DS_ScriptNode._nId++;YAHOO.widget.DS_ScriptNode.callbacks[E]=function(G){if((B.asyncMode!=="ignoreStaleResponses")||(E===YAHOO.widget.DS_ScriptNode.callbacks.length-1)){B.handleResponse(G,A,F,C);}else{}delete YAHOO.widget.DS_ScriptNode.callbacks[E];};YAHOO.widget.DS_ScriptNode._nPending++;var D=this.scriptURI+"&"+this.scriptQueryParam+"="+F+"&"+this.scriptCallbackParam+"=YAHOO.widget.DS_ScriptNode.callbacks["+E+"]";this.getUtility.script(D,{autopurge:true,onsuccess:YAHOO.widget.DS_ScriptNode._bumpPendingDown,onfail:YAHOO.widget.DS_ScriptNode._bumpPendingDown});};YAHOO.widget.DS_ScriptNode.prototype.handleResponse=function(oResponse,oCallbackFn,sQuery,oParent){var aSchema=this.schema;var aResults=[];var bError=false;var jsonList,jsonObjParsed;try{jsonList=eval("(oResponse."+aSchema[0]+")");}catch(e){bError=true;}if(!jsonList){bError=true;jsonList=[];}else{if(!YAHOO.lang.isArray(jsonList)){jsonList=[jsonList];}}for(var i=jsonList.length-1;i>=0;i--){var aResultItem=[];var jsonResult=jsonList[i];for(var j=aSchema.length-1;j>=1;j--){var dataFieldValue=jsonResult[aSchema[j]];if(!dataFieldValue){dataFieldValue="";}aResultItem.unshift(dataFieldValue);}if(aResultItem.length==1){aResultItem.push(jsonResult);}aResults.unshift(aResultItem);}if(bError){aResults=null;}if(aResults===null){this.dataErrorEvent.fire(this,oParent,sQuery,YAHOO.widget.DataSource.ERROR_DATAPARSE);aResults=[];}else{var resultObj={};resultObj.query=decodeURIComponent(sQuery);resultObj.results=aResults;this._addCacheElem(resultObj);this.getResultsEvent.fire(this,oParent,sQuery,aResults);}oCallbackFn(sQuery,aResults,oParent);};YAHOO.widget.DS_ScriptNode._bumpPendingDown=function(){YAHOO.widget.DS_ScriptNode._nPending--;};YAHOO.widget.DS_JSFunction=function(A,C){if(C&&(C.constructor==Object)){for(var B in C){this[B]=C[B];}}if(!YAHOO.lang.isFunction(A)){return ;}else{this.dataFunction=A;this._init();}};YAHOO.widget.DS_JSFunction.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_JSFunction.prototype.dataFunction=null;YAHOO.widget.DS_JSFunction.prototype.doQuery=function(C,F,D){var B=this.dataFunction;var E=[];E=B(F);if(E===null){this.dataErrorEvent.fire(this,D,F,YAHOO.widget.DataSource.ERROR_DATANULL);return ;}var A={};A.query=decodeURIComponent(F);A.results=E;this._addCacheElem(A);this.getResultsEvent.fire(this,D,F,E);C(F,E,D);return ;};YAHOO.widget.DS_JSArray=function(A,C){if(C&&(C.constructor==Object)){for(var B in C){this[B]=C[B];}}if(!YAHOO.lang.isArray(A)){return ;}else{this.data=A;this._init();}};YAHOO.widget.DS_JSArray.prototype=new YAHOO.widget.DataSource();YAHOO.widget.DS_JSArray.prototype.data=null;YAHOO.widget.DS_JSArray.prototype.doQuery=function(E,I,A){var F;var C=this.data;var J=[];var D=false;var B=this.queryMatchContains;if(I){if(!this.queryMatchCase){I=I.toLowerCase();}for(F=C.length-1;F>=0;F--){var H=[];if(YAHOO.lang.isString(C[F])){H[0]=C[F];}else{if(YAHOO.lang.isArray(C[F])){H=C[F];}}if(YAHOO.lang.isString(H[0])){var G=(this.queryMatchCase)?encodeURIComponent(H[0]).indexOf(I):encodeURIComponent(H[0]).toLowerCase().indexOf(I);if((!B&&(G===0))||(B&&(G>-1))){J.unshift(H);}}}}else{for(F=C.length-1;F>=0;F--){if(YAHOO.lang.isString(C[F])){J.unshift([C[F]]);}else{if(YAHOO.lang.isArray(C[F])){J.unshift(C[F]);}}}}this.getResultsEvent.fire(this,A,I,J);E(I,J,A);};YAHOO.register("autocomplete",YAHOO.widget.AutoComplete,{version:"2.4.0",build:"733"});


/*// script.aculo.us scriptaculous.js v1.7.0, Fri Jan 19 19:16:36 CET 2007

// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Scriptaculous = {
  Version: '1.7.0',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
  },
  load: function() {
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       parseFloat(Prototype.Version.split(".")[0] + "." +
                  Prototype.Version.split(".")[1]) < 1.5)
       throw("script.aculo.us requires the Prototype JavaScript framework >= 1.5.0");
    
    $A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider').split(',').each(
       function(include) { Scriptaculous.require(path+include+'.js') });
    });
  }
}

Scriptaculous.load();*/

