var tLeistungsSuffix;
// CurrencyFormat with sprachId
function currencyFormat(preis, sprachId){
	var dec;
	var grp;
	
	// get a minus
	var minus = '';
	preis = String(preis.toFixed(2));
	if (preis.indexOf('-') == 0) {
		minus = '-';
		preis = preis.substring(1);
	}
	
	// round to 2 decimals
	if (sprachId == "de") {
		dec = ',';
		grp = '.'; 	
	}
	else {
		dec = '.';
		grp = ',';
	}
	
	// find the decimal point
	// and get digits and fractional digits 
	var p1 = preis.indexOf('.');
	var dig;
	var frc;
	if (p1 == -1) {
		dig = preis;
		frc = '';
	}
	else {
		dig = preis.substring(0, p1);
		frc = dec + preis.substring(p1 + 1);
	}

	// insert grouping characters
	var p2 = dig.length - 3;
	var p3 = dig.length;
	var diggrp;
	if (p2 <= 0) {
		diggrp = dig;
	}
	else {
		diggrp = null;
		while (p2 >= 0) {
			var tmpgrp = dig.substring(p2, p3);
			if (diggrp == null) {
				diggrp = tmpgrp; 
			}
			else {
				diggrp = tmpgrp + grp + diggrp;
			}
			p2 -= 3;
			p3 -= 3;
		}
		if (p3 > 0) {
			diggrp = dig.substring(0, p3) + grp + diggrp;		
		}
	}

	return minus + diggrp + frc;		
}

function dateFormat(dateObject, sprachId) {
	var txt;
	var year = leadingZeros(d.getYear(), 2);
	var month = leadingZeros(d.getMonth() + 1, 2);
	var day = leadingZeros(d.getDate(), 2);	
	if (sprachId == "en") {
		txt = month + '/' + day + '/' + year; 
	}
	else {
		txt = day + '.' + month + '.' + year;
	}
	return txt; 	
}

function leadingZeros(num, n) {
	var txt = String(num);
	while (txt.length < n) {
		txt = '0' + txt;
	}
	return txt;
}

function parseDate(str) {
	var frags = str.split('-');
	var year = parseInt(frags[0], 10);
	var month = parseInt(frags[1], 10) - 1;
	var day = parseInt(frags[2], 10) - 1;
	var date = new Date(year, month, day);
	return date;
}

// removes whitespace from the beginning and end of a string
// null string will be converted to empty strings
function trim(str) {
	if (str == null) {
		return '';
	}
	var res = str.replace(/^\s*(.*?)\s*$/, '$1');
	return res;
}

// Start ajax call by submitting the specified form 
// and replace some part of the document with its result.
//
// If the form does not have an action the path of the 
// current window will be used instead.
//
// The options object may have following fields:
// - doExecuteJavascript     true|false  execute the script elements in the response
// - url                     string      url to submit the ajax request
//
function ajax_call(formElement, resultContainerId, options) {
	var url = null;
	var doExecuteJavascript = false;
	
	if (options) {
		url = trim(options.url);
		doExecuteJavascript = options.doExecuteJavascript;
	}

	// get the url
	if (url == '') {
		url = trim(formElement.action);
	}
	if (url == '') {
		url = trim(location.pathname);
	}
	options.url = url;
	options.formElement = formElement;
	options.resultContainerId = resultContainerId;
	// collect the parameters of the ajax call
	var ajaxParams = {
		url: url,
		formNode: formElement,
		mimetype: 'text/plain',
		load: function(type, data, evt) {
			options.type = type;
			options.data = data;
			options.evt = evt;
			
			// ggf. Callback-Methode starten
			if (typeof options.callback == 'function') {
				
				var result = options.callback();				
				// wenn die Callback-Methode mit false antwortet, wird die Verarbeitung abgebrochen 
				if (typeof result == 'boolean') {
					if (result == false) {
						return;
					}
				}
			}
			
			if (!data || data == '') {
				try {
					// try to log to firebug
					if (window.console && window.console.error) {
						console.error('Ajax error: no data received');
					}
				}
				catch (e) {
				}
			}
			else {
				var resultContainer = document.getElementById(resultContainerId);
	  			resultContainer.innerHTML = data;
	  			if (doExecuteJavascript == true) {
	  				executeScriptElements(resultContainer);
	  			}	  			
			}		
		},
		error: window.handleAjaxError
	};
	// make Ajax call
	dojo.io.bind(ajaxParams);
}

function ajaxLayer(formElement, resultContainerId, options, animationImage,imageId) {

	var url = null;
	var defaultImg = document.getElementById(imageId).src;
	var doExecuteJavascript = false;
	
	if (options) {
		url = trim(options.url);
		doExecuteJavascript = options.doExecuteJavascript;
	}

	// get the url
	if (url == '') {
		url = trim(formElement.action);
	}
	if (url == '') {
		url = trim(location.pathname);
	}
	
	// collect the parameters of the ajax call
	var ajaxParams = {
		url: url,
		formNode: formElement,
		mimetype: 'text/plain',
		
		load: function(type, data, evt) {
			if (!data || data == '') {
				try {
					// try to log to firebug
					if (window.console && window.console.error) {
						console.error('Ajax error: no data received');
					}
				}
				catch (e) {
				}
			}
			else {
				var resultContainer = document.getElementById(resultContainerId);
	  			resultContainer.innerHTML = data;
	  			if (doExecuteJavascript == true) {
	  				executeScriptElements(resultContainer);
	  			}
	  			if(layer){
	  				layer('true',resultContainerId);
	  			}	  				
			}
			stopImageAnimation(defaultImg,imageId);		
		},
		error: window.handleAjaxError
	};
	// start animation
	startImageAnimation(animationImage,imageId);
	// make Ajax call
	dojo.io.bind(ajaxParams);
}


// ajax Call for updating basket
function updateBasket(url,formElement) {
          	
    	formElement.ajaxAction.value = 'updateBasket';     
		// collect the parameters of the ajax call
		var ajaxParams = {
						url: url,
						formNode: formElement,
						mimetype: 'text/plain',
						load: function(type, data, evt) {
						// TODO: Redirect
							ibe_do_submit_normal('warenkorb','include','warenkorb','');		
						},
						error: window.handleAjaxError
						};

		// make Ajax call
		dojo.io.bind(ajaxParams);        
     	return true;
}

//ajax Call for updating basket
function updateMiniBasket(currentUrl, f, containerId) {
          	
    	document.getElementById('ajaxAction').value = 'updateMiniBasket';
/*    	
    	f.ajaxSessionKeyAbfrage.value = ref; 
    	f.ajaxLeistungskategorieId.value = leistungskategorieId;
    	f.ajaxTypLeistungstyp.value = typLeistungstyp;
    	f.ajaxLeistungsblockId.value = leistungsblockId;
    	f.ajaxInstitutionId.value = institutionId;
    	//f.ajaxLeistungNr.value = leistungNr;
    	f.ajaxEintragNr.value = eintragNr;
    	f.ajaxEinzelpreis.value = einzelpreis;
*/    	
    	var options = {
    		url : currentUrl,
    		doExecuteJavascript : true
    	};

    	ajax_call(f, containerId, options);
}

/*used to delete entry from tickets pre basket*/
function deleteEntryFromMiniBasket(currentUrl, f, containerId){
	var options = {
    		url : currentUrl,
    		doExecuteJavascript : true
    	};
    	ajax_call(f, containerId, options);
}

function handleAjaxError(type, error) {
			try {
				// try to log to firebug
				if (window.console && window.console.error) {
					console.error('Ajax error, type %s:  %o', type, error);
				}
			}
			catch (e) {
			}
}
// executes all script elements inside the specified html element
// this is useful if scripts that are part of an ajax response need to be processed 
function executeScriptElements(container) {
	var scripts = container.getElementsByTagName('script');
	for (var i = 0; i < scripts.length; ++i) {
		var script = scripts[i];
		var code = script.innerHTML;
		eval(code);
	}
}

// used to load Ticket Filter Block with List by Clicking at Edit button in Warenkorb
/*			hidden Inputs Needed
            <input type="hidden" name="ajaxAction" value="" />
            <input type="hidden" name="ajaxLeistungName" value="" />
            <input type="hidden" name="ajaxAnzahl" value="" />
            <input type="hidden" name="ajaxLeistungskategorieId" value="" />
            <input type="hidden" name="ajaxTypLeistungstyp" value="" />
            <input type="hidden" name="ajaxLeistungsblockId" value="" />
            <input type="hidden" name="ajaxInstitutionId" value="" />
            <input type="hidden" name="ajaxLeistungNr" value="" />
            <input type="hidden" name="ajaxKategorieNr" value="" />
            <input type="hidden" name="ajaxFirstTicketKategorieId" value="" />
*/
function load_filter(ajaxUrl,containerId, leistungName, firstTicketKategorieId, anzahl, leistungskategorieId, typLeistungstyp, leistungsblockId, institutionId, leistungNr, eintragNr, kategorieNr,animationImage,imageId) {		
	if(loadedIds[containerId]){
		layer('true',containerId);
		return true;
	}
	var f = document.Warenkorb;
	f.ajaxAction.value = 'loadfilter15100';
	f.ajaxLeistungName.value = leistungName;
	f.ajaxFirstTicketKategorieId.value = firstTicketKategorieId;
	f.ajaxAnzahl.value = anzahl;
	f.ajaxLeistungskategorieId.value = leistungskategorieId;
	f.ajaxTypLeistungstyp.value = typLeistungstyp;
	f.ajaxLeistungsblockId.value = leistungsblockId;
	f.ajaxInstitutionId.value = institutionId;
	f.ajaxLeistungNr.value = leistungNr;
	f.ajaxEintragNr.value = eintragNr;
	f.ajaxKategorieNr.value = kategorieNr;
	
	loadedIds[containerId] = true;
	
	ajaxLayer(f, containerId, {doExecuteJavascript: true, url : ajaxUrl }, animationImage,imageId);
	
   	return true;
}

// Selectbox functions used at warenkorb_ticketConfig

//function setBetrag_<%= kategorieNr %>_<%= j %>(val){
function setBetrag(betragId,selectVal,einzelpreisId,lang){
    b = 0.0;
    if (dojo.byId(einzelpreisId))
        b = dojo.byId(einzelpreisId).value;
    dojo.byId(betragId).innerHTML= currencyFormat(selectVal * parseFloat(b),lang)+"&nbsp;EUR";
    //update_sum_<%= kategorieNr %>();
}
//function clearBetrag_<%= kategorieNr %>_<%= j %>(){
function clearBetrag(betragId,selectId,lang){
	if(dojo.byId(betragId)){
   	dojo.byId(betragId).innerHTML= currencyFormat(0.0,lang)+"&nbsp;EUR"; 
    	dojo.byId(selectId).selectedIndex=0;
    	//update_sum_<%= kategorieNr %>();
	}
}                                                   
 
function clear_all(betragPrefix,selectPrefix,leistungsInfoArrayValues,language) {
	var leistungsInfoArrayList = leistungsInfoArrayValues.split(',');
	for (var index=0;index<leistungsInfoArrayList.length;index++){
		var idInputs = leistungsInfoArrayList[index];
		clearBetrag(betragPrefix+idInputs,selectPrefix+idInputs,language);						
	}
}
function loadDefaultSelect(defaultValue,warenkorbanzahlId,selectId,betragId,einzelpreisId,lang){
    b = 0.0;
    if(dojo.byId(einzelpreisId)){b = dojo.byId(einzelpreisId).value;}
    if(dojo.byId(betragId)){dojo.byId(betragId).innerHTML= currencyFormat(defaultValue * parseFloat(b),lang)+"&nbsp;EUR";}
    if(dojo.byId(selectId)){dojo.byId(selectId).selectedIndex = defaultValue;}
    if(dojo.byId(warenkorbanzahlId)){dojo.byId(warenkorbanzahlId).value = defaultValue;}
}             

function initTooltip(refEp) {
	var tooltip = dojo.widget.byId('tooltip_'+refEp);
	if (tooltip == null) {
		var tooltiplayer = dojo.byId('tooltip_'+refEp);
		tooltip = dojo.widget.createWidget('tooltip', {connectId: refEp, widgetId: 'tooltip_'+refEp}, tooltiplayer);
		tooltip._onUnHover = function (e){
			return;
		}
	}
}

function showTooltip(refEp) {
	var tooltip = dojo.widget.byId('tooltip_'+refEp);
	tooltip.open();
}

function hideTooltip(refEp) {
	var tooltip = dojo.widget.byId('tooltip_'+refEp);
	tooltip.close();
}


// Css animation
function addCSSAnimation(instance,className) {
	var oldClass = document.getElementById(instance).className;
	var newClass = oldClass+" "+className;
	document.getElementById(instance).className = newClass;
}

// Image animation start
function startImageAnimation(animationImage,imageId) {
	var imageTag = document.getElementById(imageId);	
	imageTag.src = animationImage;	
}

function stopImageAnimation(defaultImage,imageId) {
	var imageTag = document.getElementById(imageId);	
	imageTag.src = defaultImage;
}

// Provide a dummy console if firebug is not installed
if (!window.console) {
	window.console = {
		log : function() {},
		debug : function() {},
		info : function() {},
		warn : function() {},
		error : function() {},
		assert : function() {},
		dir : function() {},
		dirxml : function() {},
		trace : function() {},
		group : function() {},
		groupCollapsed : function() {},
		groupEnd : function() {},
		time : function() {},
		timeEnd : function() {},
		profile : function() {},
		profileEnd : function() {},
		count : function() {}
	};
}

// Variable
var loadedIds = new Array();

function MM_openBrWindow(theURL,winName,features) { //v2.0
 childfenster =
 window.open(theURL,winName,features);
 childfenster.focus();
}

function leeren(){
	if(document.getElementById("inputrit"))
 		document.getElementById("inputrit").value='';
}

function updateTPrice(leistungsSuffix, fo , currentUrl, animationImage, imageId,
			containerId, ref, anzahl, einzelpreis, leistungskategorieId, typLeistungstyp, leistungsblockId, institutionId, leistungNr, eintragNr) {
		
	fo = document.getElementById('f_leistung_conf');
	document.getElementById('ajaxAction').value = 'getprice';
	document.getElementById('ajaxSessionKeyAbfrage').value = ref;
	document.getElementById('ajaxAnzahlPers').value = anzahl; 
	document.getElementById('ajaxLeistungskategorieId').value = leistungskategorieId;
	document.getElementById('ajaxTypLeistungstyp').value = typLeistungstyp;
	document.getElementById('ajaxLeistungsblockId').value = leistungsblockId;
	document.getElementById('ajaxInstitutionId').value = institutionId;
	document.getElementById('ajaxLeistungNr').value = leistungNr;
	document.getElementById('ajaxEintragNr').value = eintragNr;
	document.getElementById('ajaxEinzelpreis').value = einzelpreis;
	window.tLeistungsSuffix = leistungsSuffix;
	//var resultContainerId = '';
	var options = {
		url : currentUrl,
		doExecuteJavascript : true,
		callback: updateTPriceCallback		
	};
	if(containerId){
		document.getElementById(containerId).innerHTML = "<img id='" + imageId + "' src='" + animationImage + "' />";
	}
	//startImageAnimation(animationImage,imageId);
	ajax_call(fo, containerId, options);	
	return true;
}

function updateTPriceCallback() {
	var html = this.data;
	html = html.replace(/<.*?>/g,'');
	html = html.replace('*','');
	document.getElementById(this.resultContainerId).innerHTML = html;
	document.getElementById('betrag_' + window.tLeistungsSuffix).value = html;
	
	// Weitere Javascript-Funktionen ausführen		
	//if (this.isAnzeige == true) {
		//enableAddInList(this.selectElement);
	//}
	//else {
		//getGesamtPreis(this.selectElement, this.gesamtOutputId);
	//}
	return false; // keine weitere Verarbeitung
}

function applyT_filter(f, currentUrl, ajaxAction, defaultImage, animationImage, imageId,
		containerId, ref, leistungName, abfrageNr, anzahl, leistungskategorieId, typLeistungstyp, leistungsblockId, institutionId, leistungNr, kategorieNr, eintragNr) {
	//var f = document.Warenkorb;
	f.ajaxAction.value = ajaxAction;//'filter15100';
	f.ajaxRef.value = ref;
	f.ajaxLeistungName.value = leistungName;
	f.ajaxAbfrageNr.value = abfrageNr;
	f.ajaxAnzahl.value = anzahl;
	f.ajaxLeistungskategorieId.value = leistungskategorieId;
	f.ajaxTypLeistungstyp.value = typLeistungstyp;
	f.ajaxLeistungsblockId.value = leistungsblockId;
	f.ajaxInstitutionId.value = institutionId;
	f.ajaxLeistungNr.value = leistungNr;
	f.ajaxKategorieNr.value = kategorieNr;
	f.ajaxEintragNr.value = eintragNr;
	f.ajaxFirstTicketKategorieId.value = "-1";
	if(animationImage != null) {
		startImageAnimation(animationImage, imageId);
	}
	ajax_call(f, containerId, {doExecuteJavascript: true, url : currentUrl, callback: function(){if(defaultImage != null){stopImageAnimation(defaultImage, imageId)}}});
	return true;
}