$(document).ready(function(){
	window.horzaccordion()?horzaccordion():null;
	window.makeMailLinks()?makeMailLinks():null;
	window.makeCalendar()?makeCalendar():null;
	window.makeGalleryPager()?makeGalleryPager():null;
	window.makeLightBox()?makeLightBox():null;
	window.enhanceIntFields?enhanceIntFields():null;
	window.contactEqualsDelivery?contactEqualsDelivery():null;
	window.modifyCart?modifyCart():null;
	window.linkcounter?linkcounter():null;
	window.popups?popups():null;
	window.autoSubmit?autoSubmit():null;	 		//submit form fields if the selectbox value is altered
	window.askConfirmation?askConfirmation():null;	//ask for confirmation before submiting 'dangerous' forms
	window.xmlActions?xmlActions():null;	 			// xmldo -> send a get request to the server without having to leave the page
	window.initLiveSearch?initLiveSearch():null; 		//livesearch: like google suggest
	window.books?books():null;						//add books tabber thing (to do: make this a more general tabber when needed)
	window.setMaxLength?setMaxLength():null;		//checks for textarea's with maxlength
	window.progressBars?progressBars():null;		//progress bars!
});

/* note: if MS ever releses IE 60 or up, this code will break (unless IE 60 turns out to suck) */
if($.browser.msie && jQuery.browser.version.substr(0,1) == 6){	
	browsersucks=true;
	}else{
	browsersucks=false;
	}
 /* Stop IE from caching requests (adds &_=<timestamp> to the url) */
jQuery.ajaxSetup({cache:false});

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

function horzaccordion(){
	/* get accordion width values
	 * this method has some limitations:
	 * -you need at least one active item, otherwise it doesn't know the target width
	 * -you can only have one accordion on the same page
	 * but at least the width isn't hardcoded like it was before
	 * */
	var accordionmin=$('.horzaccordion>li:not(.active)').css('width');
	var accordionmax=$('.horzaccordion>li.active').css('width');

    $(".horzaccordion li h1").click(
      function(){
	/*	 console.log($('.horzaccordion li').css('width'));
		 console.log($('.horzaccordion li.active').css('width'));*/
       $('.horzaccordion li.active').animate(
				{width: accordionmin},
				{ queue:true, duration:350 }
			); /* closing is slightly faster to avoid overflowing stuff */
		$(this).parent().animate(
			{width: accordionmax},
			{ queue:true, duration:400}
				);
		$('.horzaccordion li.active>div').fadeOut(350);
		$('.horzaccordion li.active').removeClass('active');
		$(this).next().fadeIn(400);
		$(this).parent().addClass('active');
		  }
    );
	}

/* when changing the page structure, call this */	
function refresh(){
	updateValues();
	window.popups?popups():null; 
	}


/* <span class="email">x (at) x.com</span> becomes <a href="x@x.com">x@x.com</a> 
* this is an anti-spam measure
*/
function makeMailLinks()
	{
	if (!document.getElementsByTagName && !document.createElement && !document.createTextNode)
		return;
	var spans = document.getElementsByTagName("span");
	for(var i=0;i<spans.length;i++)
		{
		if (spans[i].className=="email")
			{
			var theNode = spans[i];
			var theAddress = theNode.firstChild.nodeValue;
			
			theAddress = theAddress.replace(/ \(at\) /, "@");
			theAddressNode = document.createElement('A');
			theAddressNode.setAttribute("href", "mailto:" + theAddress);
			theAddressNode.appendChild(document.createTextNode(theAddress));
			theNode.parentNode.replaceChild(theAddressNode, theNode);
			i--; //because we implicitly removed a <span> from the spans array by making it an <a>; Otherwise it'll skip the next span
			}
		}
	}
/* calendar */

/* **************************************
start datepicker
************************************** */
//adds a datepicker next to inputfields with the 'date' class.
var calendarIcon;
var calendarClose;
function makeCalendar()	{
	calendarIcon=getroot()+'js/cal.gif';
	calendarClose=getroot()+'js/close.png';
	dateFields = $('input.date');
	for(i=0;i<dateFields.length;i++)
		{
		img = document.createElement("img");
		img.setAttribute("src",calendarIcon);
		img.setAttribute("alt","[+]");
		img.setAttribute("class","cal");
		img.onclick = function(){setDate(this);};
		img.style.cursor = "pointer";
		img.style.marginLeft = "5px";
		dateFields[i].parentNode.insertBefore(img,dateFields[i].nextSibling);
		}
	}
function setDate(e)	{
	var today = new Date();
	var month = today.getMonth() + 1;
	var day = today.getDate();
	var year = today.getFullYear();
	if(parseDate(e.previousSibling.value)){
		var existingdate = parseDate(e.previousSibling.value);
		month = existingdate[1];
		year = existingdate[0];
		}
	createDatePicker(e,month,year);
	//e.previousSibling.value=year+"-"+month+"-"+day;
	}
function createDatePicker(e,month,year)	{
	if(document.getElementById('datepicker'))
		{
		var fucker=document.getElementById('datepicker');
		fucker.parentNode.removeChild(fucker);
		}
	var calendar=document.createElement("div");
	calendar.style.position='absolute';
	/*calendar.style.border='1px solid #999';*/
	calendar.setAttribute('id','datepicker');
	/*calendar.style.background='#fff';*/
	calendar.innerHTML=calendarString(month,year);
	
	
	var fucker=document.getElementById('datepicker');
	e.parentNode.insertBefore(calendar,e.nextSibling);
	calendar.style.left=$(e).offset().left+document.body.scrollLeft+e.width+'px';
	calendar.style.top=$(e).offset().top+document.body.scrollTop+'px';
}
function parseDate(datestring){
	if(datestring.indexOf('-')>0 && datestring.split('-')[0]>0){
		return datestring.split('-');
		}else{
		return false;
		}
	}
function calendarString(month,year)	{
	string='<table id="calendartable">';
	string+='<tr class="cal_head"><td colspan="7" class="close"><img src="'+calendarClose+'" alt="click to close" onclick="closeCalendar();" /></td></tr>';
	string+='<tr>';
	string+='<td class="pickerday" onclick="changeMonth('+year+','+month+',\'prev\');return false;"><a href="#">&lt;&lt;</a></td>';
	string+='<td colspan="5" style="text-align: center;">';
	string+='<select name="month" style="width:auto;clear: none;float: none;font-size:10px;" onchange="changeMonth('+year+',this.value);">';
	for(var i=1;i<=12;i++)
		{
		string+='<option value="'+i+'"'+(month==i?' selected="selected"':null)+'>'+monthName(i)+'</option>';
		}
	string+='</select>';
	string+='<select name="year" style="width:auto;clear: none;float: none;font-size:10px;" onchange="changeMonth(this.value,'+month+');">';
	for(var i=2000;i<=2020;i++)
		{
		string+='<option value="'+i+'"'+(year==i?' selected="selected"':null)+'>'+i+'</option>';
		}
	string+='</select>';
	//string+=monthName(month);
	//string+=' '+year;
	string+='</td>';
	string+='<td class="pickerday" onclick="changeMonth('+year+','+month+',\'next\');return false;"><a href="#">&gt;&gt;</a></td>';
	string+='</tr>';
	string+='<tr>';
	string+='<td class="pickerweekday">M</td>';
	string+='<td class="pickerweekday">T</td>';
	string+='<td class="pickerweekday">W</td>';
	string+='<td class="pickerweekday">T</td>';
	string+='<td class="pickerweekday">F</td>';
	string+='<td class="pickerweekday">S</td>';
	string+='<td class="pickerweekday">S</td>';
	string+='</tr>';
	string+='<tr>';
	//calculate first weekday of the month
	var firstDayOfMonth = new Date(year,month-1,1);
	var LastDayOfMonth=daysInMonth(month,year);
	offset=(((firstDayOfMonth.getDay()+7)-1)%7);
	//draw table
	for(i=0;i<offset;i++)
		{
		string+='<td></td>';
		}
	for(i=0;i<LastDayOfMonth;i++)
		{
		if((i+offset)%7==0)	{
		string+='</tr>';	
		string+='<tr>';	
			} 
		string+='<td class="pickerday" onclick="writeDate('+year+','+month+','+(i+1)+');return false;"><a href="#">'+(i+1)+'</a></td>';
		}
	string+='</tr>';
	string+='</table>';
	return string;
	}
function monthName(monthNum)	{
	var months = new Array('january','february','march','april','may','june','july','august','september','october','november','december');
	return months[monthNum-1];
	}
// http://javascript.about.com/library/bllday.htm 
//gives the number of days in a given month. don't ask me how it works, but it does
function daysInMonth(month,year) {
	var dd = new Date(year, month, 0);
	return dd.getDate();
}
function writeDate(year,month,day)	{
	var calendar=document.getElementById('datepicker');
	if(month<10)
		{
		month='0'+month;
		}
	if(day<10)
		{
		day='0'+day;
		}
	calendar.previousSibling.previousSibling.value=year+'-'+month+'-'+day;
	closeCalendar();
	}
function changeMonth(year,month,direction)	{
	if(direction=='next')
		{
		if(month==12)	{
			month=1;
			year++;
			} else {
			month++;
			}
		} else if(direction=='prev')	{
		if(month==1)	{
			month=12;
			year--;
			} else {
			month--;
			}
		}
	var calendar=document.getElementById('datepicker');
	calendar.innerHTML=calendarString(month,year);
	}
//closecalendar
function closeCalendar()	{
var calendar=document.getElementById('datepicker');
calendar.parentNode.removeChild(calendar);
}	
/*stop calendar*/

/* *
 * linkcounter()
 * redirect all external links to a counter, which counts the click for stats, after which the user
 * gets redirected to the actual website
 * */
function linkcounter(){
	/*var externallinks = $('a.external');
	for(i=0;i<externallinks.length;i++){
		externallinks[i].onclick = function(){
				document.location=getroot()+'/xml/count.lasso?url='+encodeURI(this.href)+'&id='+$_GET('id');
				return false;
				};
		}*/
	$('a.external').attr('target','_blank').click(function(){
		document.location='http://www.efa-aef.eu/xml/count.lasso?url='+encodeURI($(this).attr('href'))+'&id='+$_GET('id');
		return false;	
		});
	}
/* php $_GET, but in JS. Winnar!
 * breaks with mod_rewrite, fail!
 *  */
function $_GET(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
	  /* workaround for mod_rewrite specific for this site */
    }else if(variable=='id'){
		var url = window.location+'';
		var chunks = url.split('/');
		return chunks[7];
	}
  } 
  return false;
}	

/* this used to be a bigger function that didn't work properly*/
function getroot(){
	return '/';
	}
String.prototype.endsWith = function(t, i) { if (i==false) { return (t
== this.substring(this.length - t.length)); } else { return
(t.toLowerCase() == this.substring(this.length -
t.length).toLowerCase()); } } 

	/* adds arrows that allow you to increment/decrement an int field*/

function enhanceIntFields()
	{
	var incrementImage=getroot()+'images/js/increment.png';
	var decrementImage=getroot()+'images/js/decrement.png';
	var intFields = $('input.int');
	for(i=0;i<intFields.length;i++)
		{
		// add - 
		img = document.createElement("img");
		img.setAttribute("src",decrementImage);
		img.setAttribute("alt","-");
		img.setAttribute("title","remove an item");
		img.setAttribute("class","fieldmodify"); //good browsers
		img.setAttribute("className","fieldmodify"); //IE
		img.onclick = function(){incrementField(this.previousSibling.previousSibling,-1);};
		intFields[i].parentNode.insertBefore(img,intFields[i].nextSibling);
		
		// add + 
		img = document.createElement("img");
		img.setAttribute("class","fieldmodify"); //good browsers
		img.setAttribute("className","fieldmodify"); //IE
		img.setAttribute("src",incrementImage);
		img.setAttribute("alt","+");
		img.setAttribute("title","add an item");
		
		img.onclick = function(){incrementField(this.previousSibling,1);};
		intFields[i].parentNode.insertBefore(img,intFields[i].nextSibling);
		
		intFields[i].onfocus = function(){this.select();}
		}
	}
function incrementField(field,amount,negative)
	{
	if((negative!=true && (parseInt(field.value)+amount)<0) ||isNaN(parseInt(field.value)))
		{
		field.value=0;
		field.setAttribute("value",0);
		field.onchange(); 
		return;
		}
	field.value=parseInt(field.value)+amount;
	field.setAttribute("value",parseInt(field.value));
	if(field.onchange)
		{
		field.onchange(); // force the onchange event
		}
	}


/* gallerypager */

var pagermaxelements=10;
function makeGalleryPager(){
	var contentafter='';
	for(var i=0;i<$('ul#gallerylisting li:nth-child('+pagermaxelements+'n)').size();i++){
			if(i==0){
				contentafter+='<span class="pageselector active" onclick="javascript:gallerypagergo('+(i+1)+',this)">'+(i+1)+'</span>';
			}else{
				contentafter+='<span class="pageselector" onclick="javascript:gallerypagergo('+(i+1)+',this)">'+(i+1)+'</span>';
			}
		}
		$('ul#gallerylisting').before(contentafter);
		$('ul#gallerylisting li:gt('+(pagermaxelements-1)+')').hide();
	}
function gallerypagergo(pager,e){
	var minel = ((pager*pagermaxelements)-pagermaxelements);
	var maxel = pager*pagermaxelements;
	$('ul#gallerylisting li').hide();
	$('ul#gallerylisting li').slice(minel,maxel).fadeIn(500);
	$('span.pageselector.active').removeClass('active');
	$(e).addClass('active');
	}

/* lightbox */
var preloadimages= new Array;
var currentlyselected ='';
function makeLightBox(){
	if($("a[rel='lightbox']")[0]){
		
		$("a[rel='lightbox']").click(function(){
			currentlyselected=this.href;
		  //$('body').append('<div id="lightbox"><p><a href="#" id="lightboxclose">Close</a><a href="#" id="lightboxnext">Next</a><a href="#" id="lightboxprev">Previous</a><!--<a href="#" id="lightboxplay">Autoplay</a>--><span>'+this.title+'</span></p><div class="imgcontainer"><div><img src="'+this.href+'" alt="loading..."/></div></div></div>');
		  
			img= new Image();
			var lightboxlink = this;
			img.onload = function(){
					//repositionLightbox();
					var topreload = new Array;
					if($(lightboxlink).parent().next().children("a[rel='lightbox']").attr('href')!=undefined)
						{
							topreload.push($(lightboxlink).parent().next().children("a[rel='lightbox']").attr('href'));
							$('#lightboxnext').removeClass('disabled');
						}
					else
						{ $('#lightboxnext').addClass('disabled');}
					if($(lightboxlink).parent().prev().children("a[rel='lightbox']").attr('href')!=undefined)
						{
							topreload.push($(lightboxlink).parent().prev().children("a[rel='lightbox']").attr('href'));
							$('#lightboxprev').removeClass('disabled');
						}
					else
						{ $('#lightboxprev').addClass('disabled');}
					for(var i=0;i<topreload.length;i++){
						var preloadimg = new Image();
						preloadimg.src=topreload[i];
						preloadimages.push(preloadimg);
						}
						$('body').append('<div id="lightbox"><p><a href="#" id="lightboxclose">Close</a><a href="#" id="lightboxnext">Next</a><a href="#" id="lightboxprev">Previous</a><!--<a href="#" id="lightboxplay">Autoplay</a>--><span>'+lightboxlink.title+'</span></p><div class="imgcontainer"><div><img src="'+lightboxlink.href+'" alt="loading..."/></div></div></div>');
						if(!browsersucks){
						  $('#lightbox').hide();
						  $('#lightbox').fadeIn('fast');
						 }
						repositionLightbox();

						$("#lightbox p a[id='lightboxnext']").click(function(){
								nextLightBoxImage();
								return false;
								});
						$("#lightbox p a[id='lightboxprev']").click(function(){
								prevLightBoxImage();
								return false;
								});
						  $('#lightbox img').click(function(){
							 $('#lightbox').remove();
							 if(browsersucks){
								$('select').show();
							}
							});
						$('#lightbox p a#lightboxplay').click(function(){
							window.alert('this isn\'t working yet');
							});
						$('#lightbox p a#lightboxclose').click(function(){
								$('#lightbox').remove();
								 if(browsersucks){
									$('select').show();
								}
								return false;
								});
							if($('#lightbox').height()<$(document).height()){
								$('#lightbox').height($(document).height()); /*fix height issues */
							}
							/* hide select boxes in IE 6 */
							if(browsersucks){
								$('select').hide();
							}
					}
	//$('#lightboxplay').hide();		
				
			img.src=this.href;
			repositionLightbox();
		
		return false;
		});
	

	}
}
function repositionLightbox(){
	margintop=parseInt(($(window).height()-$('div#lightbox div.imgcontainer img').height())/2);
	//window.alert(margintop);
		$('div#lightbox div.imgcontainer').css({'margin-top':margintop+'px'});
		if(browsersucks || ($.browser.msie && jQuery.browser.version.substr(0,1) == 7)){
			window.setTimeout(function(){
			scrolltop=$('html').scrollTop();
			margintop=parseInt(($(window).height()-$('div#lightbox div.imgcontainer img').height())/2);
				if(browsersucks){
					$('div#lightbox div.imgcontainer').css({'margin-top':scrolltop+margintop+'px'});
				}else{
					$('div#lightbox div.imgcontainer').css({'margin-top':margintop+'px'});
				}
			},100);
		}
	}
function getAllimages(){
	var lightboximages= new Array();
	$("a[rel='lightbox']").each(function(){lightboximages.push(this);});
	return lightboximages;
	}
function nextLightBoxImage(){
	/* figure out who's next (if applicable) */
	var lightboximages = getAllimages();
	for(var i=0;i<lightboximages.length;i++){
		if(lightboximages[i].href==currentlyselected && i<lightboximages.length-1){
			lightboxShowImage(lightboximages[i+1].href,lightboximages[i].href,'next',lightboximages[i+1].title,i+1,lightboximages.length);
			return;
			}
		}
	}
function prevLightBoxImage(){
	var lightboximages = getAllimages();
	for(var i=0;i<lightboximages.length;i++){
		if(lightboximages[i].href==currentlyselected && i>0){
			lightboxShowImage(lightboximages[i-1].href,lightboximages[i].href,'prev',lightboximages[i-1].title,i-1,lightboximages.length);
			return;
			}
		}
	}
function lightboxShowImage(url,current,dir,title,imagenum,imagecount){
	if(url!=undefined){
		currentlyselected=url;
		$('.imgcontainer div img').attr('src',url);
		$('#lightbox span').text(title);
		repositionLightbox();
		if(imagenum==0){
			$('#lightboxprev').addClass('disabled');
			}else{
			$('#lightboxprev').removeClass('disabled');
			}
		if(imagenum==imagecount-1){
			$('#lightboxnext').addClass('disabled');
			}else{
			$('#lightboxnext').removeClass('disabled');
			}
		}
	}

function checkKey(e){
     switch (e.keyCode) {
        case 37:
			if($('#lightbox').length>0){prevLightBoxImage();}
            break;
        case 39:
            if($('#lightbox').length>0){nextLightBoxImage();}
            break;
        default:
         
            }      
}



/* *******************************************
add popup events when there's a class="popup" on a link
******************************************** */
function popups()	{
	var popuplinks = new Array;
	popuplinks = $('a.popup');
	for(i=0;i<popuplinks.length;i++)
		{
		width=550;
		height=450;
		popuplinks[i].onclick=function(){ popup(this.href,width,height);return false;};
		}
	}
function popup(url,windowwidth,windowheight)	{
	window.open(url,'upload','width='+windowwidth+',height='+windowheight+',scrollbars=1');
	}
/* when you're a popup window, refresh stuff on parent window when loading */	
if(self.opener)
	{
	self.opener.flushXMLData?self.opener.flushXMLData():null;
	}
function flushXMLData()	{
	$('.xmlget').each(function(){
		$(this).load(
			$(this).prev()[0].href,'',function(){
				window.xmlActions?xmlActions():null;
				}
			);
		});
	
	}
/* ************************************************************************************************
ask confirmation before submitting a form (<form class="confirm" title="are you sure you want to drop this database?">)
************************************************************************************************ */
function askConfirmation()
	{
	confirmations = $('form.confirm');
	for(i=0;i<confirmations.length;i++)
		{
		//inventing new attributes
		confirmations[i].setAttribute('confirm',confirmations[i].title);
		confirmations[i].title="";
		confirmations[i].onsubmit = function(){return window.confirm(this.getAttribute('confirm'));};
		
		}
	}

/* ******************************
submits forms when the selectbox has a class of 'submitonchange'
also hides submit buttons with class of 'jshide'
****************************** */
function autoSubmit()	{
	$('.jshide').hide();
	$('select.submitonchange').change(function(){submitForm(this)});
	}
function submitForm(e){
	e.parentNode.parentNode.submit();
	}

	
/* shopping cart functions 
* note that the cart should still function if js is disabled, don't use this to do calculations and such
*
*/

/* disable delivery fields if the checkbox  'contactequalsdelivery'is checked
and yes, i could've picked a longer id if I wanted to.
 */
function contactEqualsDelivery(){
	var checkbox=$('#contactequalsdelivery');
		if(checkbox)
		{
		checkbox.change(function()
			{
			setDisabled('delivery',this.checked);
			});

		checkbox.click(function(){
			//this.change();
			setDisabled('delivery',this.checked);
			});
		 

		}	
	}
/* use this to enable/disable a bunch of input fields using their class name */	
function setDisabled(classname,which)
	{
	var fields = $('input.'+classname+',select.'+classname);
		for(i=0;i<fields.length;i++)
			{
		//	console.log(which);
			fields[i].disabled=which;
			// needed for IE 
			if(which==true)
				{
				fields[i].style.backgroundColor='#ddd';
				}else{
				fields[i].style.backgroundColor='';
				}
			}
	}
/* onchange, submit 
*/
function modifyCart(){
	var cartmodify = $('form.cartmodify');
	// add submit onchange to every input element 
	for(var i=0;i<cartmodify.length;i++)
		{
		addSubmitOnChange(cartmodify[i]);
		}
	}
function addSubmitOnChange(form)	{
	var nodes = form.childNodes;
	var inputfields = new Array;
	for(var i=0;i<nodes.length;i++)
		{
		if(nodes[i].tagName=='INPUT')
			{
			nodes[i].onchange = function()
				{
				//submit the form you're in
				// this part should be replaced by an xmlHTTPRequest POST to self containing all the form values
				//followed by an update of parts of the page
				
				backgroundSubmit(form);
				//form.submit();
				}
			// IE needs this because it's standards-compliant for once 
			if(nodes[i].getAttribute('type')=='radio')
				{
				nodes[i].onclick = function (){
					//this.blur(); 
					this.onchange(); // forces the event to fire in IE and Safari 2 after clicking a radio button. Apparently this is according to the specs
					//if(this.onchange=='something'){}
						
					}
				}
			}else if(nodes[i].tagName=='BUTTON'){
				if(nodes[i].className=='updatebutton')
					{
					nodes[i].style.display='none';
					}
			}
		}
	}
	
	
function updateValues()
	{
	/* get all elements that can apply for an update */
	var async=$('.async');
	var root = getroot();
	/* loop through async, and update each element */
	for(var i=0;i<async.length;i++)
		{
		var asyncId=async[i].id;
		var asyncParams=asyncId.split('_'); 
		var requesturl=root+'xml/'+asyncParams.shift()+'.lasso?params='+asyncParams.join('_');
		$('#'+asyncId).load(requesturl);
		}
	}
	
	
function incrementField(field,amount,negative)
	{
	if((negative!=true && (parseInt(field.value)+amount)<0) ||isNaN(parseInt(field.value)))
		{
		field.value=0;
		field.setAttribute("value",0);
		field.onchange(); 
		return;
		}
	field.value=parseInt(field.value)+amount;
	field.setAttribute("value",parseInt(field.value));
	if(field.onchange)
		{
		field.onchange(); // force the onchange event
		}
	}
/* /end shopping cart functions */	
/* ******************************************************************************
xmlHTTPRequest stuff 
****************************************************************************** */
/* submit a form in the background, instead of using a page reload */
function backgroundSubmit(form)	{
var target=form.action;

/* target is the target where the post should go*/
/* now get the values of the input fields in the form*/
var nodes = form.childNodes;
var inputfields = new Array;
	for(var i=0;i<nodes.length;i++)
		{
		if(nodes[i].tagName=='INPUT'|| nodes[i].tagName=='TEXTAREA' )
			{
			var sendparam=true;
			if(nodes[i].type=='radio' && nodes[i].checked==false)
				{
				sendparam=false;
				}
			if(sendparam)
				{
				inputfields.push(nodes[i]);
				}
			}
		}
/* construct a POST string */
var post = new Array;
for(var i=0;i<inputfields.length;i++)
	{
	post.push(inputfields[i].getAttribute('name')+'='+inputfields[i].getAttribute('value'));
	}
var poststring = post.join('&');
//sendXmlHTTPRequest('POST',target,poststring);
$.ajax({
      type: "POST",
      url: target,
      data: poststring,
      success: function() {
		refresh();
      }
     });
}

//this one just loads a page (without immediate feedback)
function xmlActions()	{
		$('a.xmldo').click(function(){
			$('this').blur();
			/* Do HEAD request */
			var head= jQuery.ajax({
		      type: "HEAD",
		      url: this.href,
		      data: '',
		      complete: function () {
				  flushXMLData();
		      }
		    });
			return false;
			});
	}

/* *******************************************
add live search on specific form elements (  like in http://www.google.com/webhp?complete=1 )
******************************************** */
function initLiveSearch()	{
	var searching;
	var livesearchinputs = new Array;
	livesearchinputs = $('input.live');
	for(i=0;i<livesearchinputs.length;i++)
		{
		//arr=getClassVariables(livesearchinputs[i],'livesearch');
		livesearchinputs[i].setAttribute('live',livesearchinputs[i].title);
		livesearchinputs[i].title="";
		livesearchinputs[i].onkeyup=function(){ liveSearch(this,this.value,this.getAttribute('live'),10);return false;};
		}
	}
var searching;
function liveSearch(e,query,url,height)	{
	if(searching)
		{
		clearTimeout(searching);
		}
	if(query=='')
		{
		$('#livesearch').remove();
		} else	{
		if(!document.getElementById('livesearch'))
			{
				div = document.createElement("div");
				div.setAttribute("id","livesearch");
				inputFieldPosition = $(e).offset();
				//console.log(inputFieldPosition);
				div.style.left=inputFieldPosition.left+'px';
				div.style.top=inputFieldPosition.top+$(e).height()+5+'px';
				e.parentNode.insertBefore(div,e);
			/*	$('#livesearch').css('margin-left'='300px');
				$('#livesearch').css('margin-top'='20px');*/
				//document.body.onclick(function(){this.style.background='#fff'});
				$('body').click( function(event) {
					//console.log('clicked');
					$('#livesearch').remove();
					});

			} else	{
				div=e.previousSibling;
			}
		//div.innerHTML="livesearch: "+query;
		
		var xmlquery = getroot()+'xml/'+url+'?query='+escape(query);
		searching = setTimeout(function(){
				$('#livesearch').load(xmlquery);
				},500);
		}
	}
	
function books() {
	
 	$("div"+$('ul#books>li>a.active').attr('href')).fadeIn("slow");

	$('ul#books>li>a').click(function() {
	
			$('ul#books>li>a').removeClass('active');
			var tofadein = $(this);
 			$("div.books:visible").fadeOut(500,function(){
				$("div"+tofadein.attr('href')).fadeIn("slow");
				tofadein.addClass('active');
				});
			return false;
			
		}
	);
}

/* **************************
PPK's awesome form maxlength script
*************************** */
function setMaxLength() {
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].className=='maxlength') {
			var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			var maxLength = x[i].previousSibling.value;
			counterClone.innerHTML = '<span>0</span>/'+maxLength;
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];
			x[i].onkeyup = x[i].onchange = checkMaxLength;
			x[i].onkeyup();
		}
	
	}
}


function checkMaxLength() {
	var maxLength = this.previousSibling.value;
	var currentLength = this.value.length;
	if (currentLength > maxLength)
	{
		this.className = 'toomuch';
		this.value = this.value.substring(0,maxLength); 
		this.focus();
	}else{
		this.className = 'maxlength';
	this.relatedElement.firstChild.nodeValue = currentLength;
	}
	// not innerHTML
}

/* stop maxlength script */

function progressBars(){
	if($('.progressbar').size()>0){
		updateProgressBar();
		var progbartimer = window.setInterval(function(){updateProgressBar();},5000);
		}
	}
function updateProgressBar(){
	$('.progressbar').each(function(){
		var url = $(this).children('.data').text();
		$.getJSON(url, function(data) {
			var progressbar = $('.progressbar .data:contains('+url+')').parent();
  			if(data.progress==data.total){
				progressbar.addClass('complete');
				progressbar.children('.bar').width('100%');
				window.location=window.location.href;
			}else{
				var newwidth = parseInt(data.progress/data.total*progressbar.width(),10);
				if(newwidth>parseInt(progressbar.children('.bar').width(),10)){
  					progressbar.children('.bar').animate({width:newwidth},4000,'linear');
					}else{
					progressbar.children('.bar').animate({width:'100%'},1000,'linear',function(){
						window.location=window.location.href;
						});
					
					}
				}
			});
		});
	
	}

