/****************** Zusatzscript *******************/

function openWindow (url,title,attributes) {
  	var myWindow = window.open(Aurl, title, attributes);
  	myWindow.focus();
}


function is_array(value) {
	if (typeof value === 'object' && value && value instanceof Array) {
		return true;
	}
	return false;
}

function str_replace(s, r, c) {
	if (is_array(s)) {
		for(i=0; i < s.length; i++) {
			c = c.split(s[i]).join(r[i]);
		}
	}
	else {
		c = c.split(s).join(r);
	}
	return c;
}

function date(format, timestamp) {

    var that = this,
        jsdate, f, formatChr = /\\?([a-z])/gi, formatChrCb,
        // Keep this here (works, but for code commented-out
		// below for file size reasons)
        //, tal= [],
        _pad = function (n, c) {
            if ((n = n + "").length < c) {
                return new Array((++c) - n.length).join("0") + n;            } else {
                return n;
            }
        },
        txt_words = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur",        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"],
        txt_ordin = {
            1: "st",
            2: "nd",            3: "rd",
            21: "st",
            22: "nd",
            23: "rd",
            31: "st"        };
    formatChrCb = function (t, s) {
        return f[t] ? f[t]() : s;
    };
    f = {    // Day
        d: function () { // Day of month w/leading 0; 01..31
            return _pad(f.j(), 2);
        },
        D: function () { // Shorthand day name; Mon...Sun
        return f.l().slice(0, 3);
        },
        j: function () { // Day of month; 1..31
            return jsdate.getDate();
        },        l: function () { // Full day name; Monday...Sunday
            return txt_words[f.w()] + 'day';
        },
        N: function () { // ISO-8601 day of week; 1[Mon]..7[Sun]
            return f.w() || 7;        },
        S: function () { // Ordinal suffix for day of month; st, nd, rd, th
            return txt_ordin[f.j()] || 'th';
        },
        w: function () { // Day of week; 0[Sun]..6[Sat]
        return jsdate.getDay();
        },
        z: function () { // Day of year; 0..365
            var a = new Date(f.Y(), f.n() - 1, f.j()),
                b = new Date(f.Y(), 0, 1);
				return Math.round((a - b) / 864e5) + 1;
        },

    // Week
        W: function () { // ISO-8601 week number
        	var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3),
            b = new Date(a.getFullYear(), 0, 4);
            return 1 + Math.round((a - b) / 864e5 / 7);
        },
     // Month
        F: function () { // Full month name; January...December
            return txt_words[6 + f.n()];
        },
        m: function () { // Month w/leading 0; 01...12
        return _pad(f.n(), 2);
        },
        M: function () { // Shorthand month name; Jan...Dec
            return f.F().slice(0, 3);
        },        n: function () { // Month; 1...12
            return jsdate.getMonth() + 1;
        },
        t: function () { // Days in month; 28...31
            return (new Date(f.Y(), f.n(), 0)).getDate();        },

    // Year
        L: function () { // Is leap year?; 0 or 1
            var y = f.Y(), a = y & 3, b = y % 4e2, c = y % 1e2;
			return 0 + (!a && (c || !b));
        },
        o: function () { // ISO-8601 year
            var n = f.n(), W = f.W(), Y = f.Y();
            return Y + (n === 12 && W < 9 ? -1 : n === 1 && W > 9);        },
        Y: function () { // Full year; e.g. 1980...2010
            return jsdate.getFullYear();
        },
        y: function () { // Last two digits of year; 00...99
        return (f.Y() + "").slice(-2);
        },

    // Time
        a: function () { // am or pm
        return jsdate.getHours() > 11 ? "pm" : "am";
        },
        A: function () { // AM or PM
            return f.a().toUpperCase();
        },        B: function () { // Swatch Internet time; 000..999
            var H = jsdate.getUTCHours() * 36e2, // Hours
                i = jsdate.getUTCMinutes() * 60, // Minutes
                s = jsdate.getUTCSeconds(); // Seconds
            return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3);        },
        g: function () { // 12-Hours; 1..12
            return f.G() % 12 || 12;
        },
        G: function () { // 24-Hours; 0..23
        return jsdate.getHours();
        },
        h: function () { // 12-Hours w/leading 0; 01..12
            return _pad(f.g(), 2);
        },        H: function () { // 24-Hours w/leading 0; 00..23
            return _pad(f.G(), 2);
        },
        i: function () { // Minutes w/leading 0; 00..59
            return _pad(jsdate.getMinutes(), 2);        },
        s: function () { // Seconds w/leading 0; 00..59
            return _pad(jsdate.getSeconds(), 2);
        },
        u: function () { // Microseconds; 000000-999000
        return _pad(jsdate.getMilliseconds() * 1000, 6);
        },

    // Timezone
        e: function () {
		// Timezone identifier; e.g. Atlantic/Azores, ...
		// The following works, but requires inclusion of the very large
		// timezone_abbreviations_list() function.
		/*
		  	return this.date_default_timezone_get();
		*/
            throw 'Not supported (see source code of date() for timezone on how to add support)';        },
        I: function () { // DST observed?; 0 or 1
            // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC.
            // If they are not equal, then DST is observed.
            var a = new Date(f.Y(), 0), // Jan 1
            	c = Date.UTC(f.Y(), 0), // Jan 1 UTC
                b = new Date(f.Y(), 6), // Jul 1
                d = Date.UTC(f.Y(), 6); // Jul 1 UTC
            return 0 + ((a - c) !== (b - d));
        },        O: function () { // Difference to GMT in hour format; e.g. +0200
            var a = jsdate.getTimezoneOffset();
            return (a > 0 ? "-" : "+") + _pad(Math.abs(a / 60 * 100), 4);
        },
        P: function () { // Difference to GMT w/colon; e.g. +02:00
        	var O = f.O();
            return (O.substr(0, 3) + ":" + O.substr(3, 2));
        },
        T: function () { // Timezone abbreviation; e.g. EST, MDT, ...
						// The following works, but requires inclusion of the very
						// large timezone_abbreviations_list() function.
/*
  			var abbr = '', i = 0, os = 0, default = 0;
            if (!tal.length) {
                tal = that.timezone_abbreviations_list();
            }
            if (that.php_js && that.php_js.default_timezone) {
                default = that.php_js.default_timezone;
                for (abbr in tal) {
                    for (i=0; i < tal[abbr].length; i++) {
                        if (tal[abbr][i].timezone_id === default) {
                        	return abbr.toUpperCase();
                        }
                    }
                }
            }
            for (abbr in tal) {
                for (i = 0; i < tal[abbr].length; i++) {
                    os = -jsdate.getTimezoneOffset() * 60;
                    if (tal[abbr][i].offset === os) {
                        return abbr.toUpperCase();
                    }
                }
            }
*/
            return 'UTC';

		},
        Z: function () { // Timezone offset in seconds (-43200...50400)
            return -jsdate.getTimezoneOffset() * 60;
        },
     // Full Date/Time
        c: function () { // ISO-8601 date.
            return 'Y-m-d\\Th:i:sP'.replace(formatChr, formatChrCb);
        },
        r: function () { // RFC 2822
        return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb);
        },
        U: function () { // Seconds since UNIX epoch
            return jsdate.getTime() / 1000 | 0;
        }
	};
    this.date = function (format, timestamp) {
        that = this;
        jsdate = (
            (typeof timestamp === 'undefined') ? new Date() : // Not provided
            (timestamp instanceof Date) ? new Date(timestamp) : // JS Date()
            new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
        );
        return format.replace(formatChr, formatChrCb);
    };
	return this.date(format, timestamp);
}

function strtotime (str, now) {
    
    var i, match, s, strTmp = '', parse = '';

    strTmp = str;    strTmp = strTmp.replace(/\s{2,}|^\s|\s$/g, ' '); // unecessary spaces
    strTmp = strTmp.replace(/[\t\r\n]/g, ''); // unecessary chars

    if (strTmp == 'now') {
        return (new Date()).getTime()/1000; // Return seconds, not milli-seconds
    } else if (!isNaN(parse = Date.parse(strTmp))) {
        return (parse/1000);
    } else if (now) {
        now = new Date(now*1000); // Accept PHP-style seconds
    } else {
		now = new Date();
    }

    strTmp = strTmp.toLowerCase();
     var __is =
    {
        day:
        {
            'sun': 0,            'mon': 1,
            'tue': 2,
            'wed': 3,
            'thu': 4,
            'fri': 5,            'sat': 6
        },
        mon:
        {
            'jan': 0,            'feb': 1,
            'mar': 2,
            'apr': 3,
            'may': 4,
            'jun': 5,            'jul': 6,
            'aug': 7,
            'sep': 8,
            'oct': 9,
            'nov': 10,            'dec': 11
        }
    };

    var process = function (m) {        var ago = (m[2] && m[2] == 'ago');
        var num = (num = m[0] == 'last' ? -1 : 1) * (ago ? -1 : 1);

        switch (m[0]) {
            case 'last':            case 'next':
                switch (m[1].substring(0, 3)) {
                    case 'yea':
                        now.setFullYear(now.getFullYear() + num);
                        break;                    case 'mon':
                        now.setMonth(now.getMonth() + num);
                        break;
                    case 'wee':
                        now.setDate(now.getDate() + (num * 7));                        break;
                    case 'day':
                        now.setDate(now.getDate() + num);
                        break;
                    case 'hou':                        now.setHours(now.getHours() + num);
                        break;
                    case 'min':
                        now.setMinutes(now.getMinutes() + num);
                        break;                    case 'sec':
                        now.setSeconds(now.getSeconds() + num);
                        break;
                    default:
                        var day;                        if (typeof (day = __is.day[m[1].substring(0, 3)]) != 'undefined') {
                            var diff = day - now.getDay();
                            if (diff == 0) {
                                diff = 7 * num;
                            } else if (diff > 0) {                                if (m[0] == 'last') {diff -= 7;}
                            } else {
                                if (m[0] == 'next') {diff += 7;}
                            }
                            now.setDate(now.getDate() + diff);                        }
                }
                break;

            default:                if (/\d+/.test(m[0])) {
                    num *= parseInt(m[0], 10);

                    switch (m[1].substring(0, 3)) {
                        case 'yea':                            now.setFullYear(now.getFullYear() + num);
                            break;
                        case 'mon':
                            now.setMonth(now.getMonth() + num);
                            break;                        case 'wee':
                            now.setDate(now.getDate() + (num * 7));
                            break;
                        case 'day':
                            now.setDate(now.getDate() + num);                            break;
                        case 'hou':
                            now.setHours(now.getHours() + num);
                            break;
                        case 'min':                            now.setMinutes(now.getMinutes() + num);
                            break;
                        case 'sec':
                            now.setSeconds(now.getSeconds() + num);
                            break;                    }
                } else {
                    return false;
                }
                break;        }
        return true;
    };

    match = strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(?:\s(\d{1,2}:\d{2}(:\d{2})?)?(?:\.(\d+))?)?$/);    if (match != null) {
        if (!match[2]) {
            match[2] = '00:00:00';
        } else if (!match[3]) {
            match[2] += ':00';        }

        s = match[1].split(/-/g);

        for (i in __is.mon) {            if (__is.mon[i] == s[1] - 1) {
                s[1] = i;
            }
        }
        s[0] = parseInt(s[0], 10);
        s[0] = (s[0] >= 0 && s[0] <= 69) ? '20'+(s[0] < 10 ? '0'+s[0] : s[0]+'') : (s[0] >= 70 && s[0] <= 99) ? '19'+s[0] : s[0]+'';
        return parseInt(this.strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2])+(match[4] ? match[4]/1000 : ''), 10);
    }
     var regex = '([+-]?\\d+\\s'+
        '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+
        '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday'+
        '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday)'+
        '|(last|next)\\s'+        '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+
        '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday'+
        '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday))'+
        '(\\sago)?';
     match = strTmp.match(new RegExp(regex, 'gi')); // Brett: seems should be case insensitive per docs, so added 'i'
    if (match == null) {
        return false;
    }
     for (i = 0; i < match.length; i++) {
        if (!process(match[i].split(' '))) {
            return false;
        }
    }
    return (now.getTime()/1000);
}

function init_tooltip(){
	var customTips = $$('.tooltip');
	var toolTips = new Tips(customTips, {
        //this will set how long before
        //the tooltip will wait to show up
        //when you mouseover the element
        //in milliseconds
        showDelay: 100,    //default is 100

        //this is how long the tooltip
        //will delay bofore hiding
        //when you leave
        hideDelay: 100,   //default is 100

        //this will add a wrapper div
        //with the following class to your tooltips
        //this lets you have different styles of tooltips
        //on the same page
        className: 'anything', //default is null

        //this sets the x and y offets
        offsets: {
                'x': 16,       //default is 16
                'y': 16        //default is 16
        },

        //this determines whether the tooltip
        //remains staitionary or follows your cursor
        //true makes it stationary
         fixed: false,      //default is false

        //if you call the functions outside of the options
        //then it may "flash" a bit on transitions
        //much smoother if you leave them in here
        onShow: function(toolTipElement){
            //passes the tooltip element
                //you can fade in to full opacity
                //or leave them a little transparent
            toolTipElement.fade(.95);
        },
        onHide: function(toolTipElement){
            toolTipElement.fade(0);
        }
	});
}

function init_zipcrawler(){
	//console.log('zipcrawler');
	$('newevent_7').addEvent('change', function(e){
		var zip = $('newevent_6').get('value');
		var zip = zip.length == 5 ? zip : false;
		var city = this.get('value');
		var cname = this.options[this.selectedIndex].text;
		if (city && $('newevent_6').get('value').length <= 5) {
			$('newevent_6').setStyle('backgroundColor','#cdcdcd');
			var req = new Request.HTML({
				url: 'index.php?id=54',
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
					$('newevent_6').getParent().set('html', responseHTML);
					init_citycrawler();
					if (cname != '' && cname != 'Bitte Standort wählen') {
						var search = $('newevent_6').get('value') + ' ' + cname;
						//console.log(search);
						showAddress(search, '', true);
					}

				},
				update: $('newevent_6')
			}).post({
				mod: 'getZip',
				city: city,
				zip: zip
			});
		}



	})
}

function init_citycrawler(){
	//console.log('citycrawler');
	$('newevent_6').addEvent('keyup', function(e){
		var plz = this.get('value');
		if(plz.match(/^\d{0,5}$/)){

			if (plz.length == 0 || plz.length == 5) {
				$('newevent_7').setStyle('backgroundColor','#cdcdcd');
				var req = new Request.HTML({
					url: 'index.php?id=54',
					onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
						$('newevent_7').getParent().set('html', responseHTML);
						init_zipcrawler();

						if($('newevent_7').get('value') > 0){
							var cname = $('newevent_7').options[$('newevent_7').get('value')].text;
							var search = $('newevent_6').get('value')+' '+cname;
							//console.log(search);
							showAddress(search,'',true);
						}
					},
					update: $('newevent_7')
				}).post({
					mod: 'getCities',
					zip: plz
				});
			}

		}else{
			var substr = plz.substring(0,plz.length-1);
			this.set('value',substr);
		}

	})

	if($('newevent_7').get('value') > 0 && $('loadevent_1').get('value') == '' && $('loadevent_2').get('value') == ''){
		var lat = $('coordX').get('value');
		var lon = $('coordY').get('value');
		var search = lat+','+lon;
		//console.log(search);
		//showAddress(search,'',true);
	}
}

function init_navigation(){
	if($$('.calendarium .navigation')){

		$$('.calendar-marker').addLiveEvent('click','img',function(e){

			var next = this.getParent().hasClass('next');
			var span = this.getParent().getParent().getChildren('.current-yearmonth')[0];
			var month = span.getChildren('.current-month').get('class')[0].split(' ')[1].split('-')[1];			
			var year = span.getChildren('.current-year').get('class')[0].split(' ')[1].split('-')[1];

			if(next){
				if(this.getParent().hasClass('nextyear')){
					year++;
				}else{
					month++;
					if(month == 13){
						month = 1;
						year++;
					}
				}
			}else{
				if (this.getParent().hasClass('prevyear')) {
					year--;
				}
				else {
					month--;
					if (month == 0) {
						month = 12;
						year--;
					}
				}
			}

			var url = document.location.toString();

			var field = this.getParent().getParent().getParent().getParent().getParent().getParent().getParent().get('id');
			new Element("div", {id: "loading"}).inject($(field));

			var persons = 0;
			var arrival = false;
			var departure = false;

			if($('erwachsene')){
				persons = parseInt($('erwachsene').get('value'),10) + parseInt($('kinder').get('value'),10);
			}
			if($('arrival')){
				arrival = $('arrival').get('value');
			}
			if($('departure')){
				departure = $('departure').get('value');
			}else if(arrival){
				var tmp = arrival.split('.');
				tmp = tmp[2]+'-'+tmp[1]+'-'+tmp[0];
				departure = date('d.m.Y',strtotime(tmp)+parseInt($('duration').get('value'),10)*86400);
			}

			var req = new Request.HTML({
				url:url,
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
								$(field).set('html',responseHTML);
								init_tooltip();
							}
			}).post({mod:'getCalendar',year:year,month:month,field:field,persons:persons,arrival:arrival,departure:departure,navigation:true});

		})
	}

	/** Markierung der Reisetage */
	$$('#onlinebuchung .calendar-marker').addLiveEvent('click','.doy-link',function(e){

		e.preventDefault();

		var fieldid = this.getParents('.calendar-marker').get('id').toString();
		var field = fieldid.split('-');
		field = field[field.length-1];
	//	console.log(field);
		$$('#'+fieldid+' .td-doy').removeClass('arrival');
		$$('#'+fieldid+' .td-doy').removeClass('staydate');
		$$('#'+fieldid+' .td-doy').removeClass('departure');
		$$('#'+fieldid+' .td-doy').set('title','');
	
		var datum = this.getParent('td').get('class').split('_')[1];
		//console.log(datum);
		var tmp = datum.split('-');
		var day = tmp[2] + '.' + tmp[1] + '.' + tmp[0];
		$(field).set('value',day);

		

		if (field == 'arrival') {
			this.getParent('td').addClass('arrival');
			this.getParent('td').set('title', 'Anreise');
		}else{
			this.getParent('td').addClass('departure');
			this.getParent('td').set('title', 'Abreise');
		}
		

		if ($('duration')) {
			var dura = parseInt($('duration').get('value'), 10);
			//console.log(datum);
			var start = strtotime(datum)+86400;
			//console.log(start);
			var end = start+(dura-1)*86400;
			//console.log(end);
			for (i = start; i <= end; i+=86400) {
				//alert(i);
				
				var ndate = date('Y-m-d',i);
				//console.log(ndate);
				var nclass = i < end ? 'staydate' : 'departure';
				$$('#'+fieldid+' .td-doy').each(function(element){
					if(element.get('rel') == ndate){
						element.addClass(nclass);
					}
				})
				
			}
		}else if(field == 'arrival'){
			init_checkup(2);
		}else if(field == 'departure'){
			
			var day = $('arrival').get('value').split('.');
			
			var start = strtotime(day[2] + '-' + day[1] + '-' + day[0]);
			var end = strtotime(this.getParent('td').get('class').split('_')[1].split(' ')[0]);
			//console.log(end);
			for (i = start; i < end; i+=86400) {
				//alert(i);
				
				var nclass = i < end ? 'staydate' : 'departure';
				var ndate = date('Y-m-d',i);
				$$('#'+fieldid+' .free').each(function(element){
					var dateclass = 'cell_'+ndate;
					//console.log(element.hasClass(dateclass));
					if(element.hasClass(dateclass)){
						element.addClass(nclass);
					}
				})
				
			}
		}
	})
}

Element.implement({
	addLiveEvent: function(event, selector, fn){
		this.addEvent(event, function(e){
	    	var t = $(e.target);
			if (!t.match(selector)) return e;
	        fn.apply(t, [e]);
		}.bindWithEvent(this, selector, fn));
    }
});


function init_checkup(fieldrefresh)
{
	var refresh = fieldrefresh ? fieldrefresh : 'all';
	var persons = parseInt($('erwachsene').get('value'),10) + parseInt($('kinder').get('value'),10);
	var rooms = false;
	var idShelter = false;

	if (persons > 0) {
		var arrival = $('arrival').get('value');

		var day_a = arrival.split('.')[0];
		var month_a = arrival.split('.')[1];
		var year_a = arrival.split('.')[2];

		var departure = false;
		var fields = 1;
		if ($('departure')) {
			var fields = 2;
			departure = $('departure').get('value');
			var month_d = departure.split('.')[1];
			var year_d = departure.split('.')[2];
			rooms =  parseInt($('zimmer').get('value'),10)
			idShelter = parseInt($('zimmerart').get('value'),10);
		}else if($('duration')){
			var dura = parseInt($('duration').get('value'),10);
			var start = year_a+'-'+month_a+'-'+day_a+' 00:00:00';
			var tstamp = parseInt(strtotime(start),10) + parseInt((dura-1)*86400,10);
			var ende = date('d.m.Y',tstamp);

			departure = ende.toString();

		}

		if (refresh == 'all' || refresh == 1) {
			new Element("div", {
				id: "loading"
			}).inject($('calendar-marker-arrival'));
			var req = new Request.HTML({
				url: document.location.toString(),
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
					$('calendar-marker-arrival').set('html', responseHTML);
					init_tooltip();
				}
			}).post({
				mod: 'getCalendar',
				year: year_a,
				month: month_a,
				field: 'calendar-marker-arrival',
				persons: persons,
				rooms: rooms,
				idShelter: idShelter,
				arrival: arrival,
				departure: departure
			});
		}
		
		if (fields == 2 && (refresh == 'all' || refresh == 2)) {
			new Element("div", {
				id: "loading"
			}).inject($('calendar-marker-departure'));
			var req = new Request.HTML({
				url: document.location.toString(),
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
					$('calendar-marker-departure').set('html', responseHTML);
									
					var val1 = 0;
					if($$('#calendar-marker-departure .departure')){
						var val1 = strtotime($$('#calendar-marker-departure .departure').get('rel').toString());
					}
					
					var dep = $('departure').get('value').split('.');
					var val2 = strtotime(dep[2]+'-'+dep[1]+'-'+dep[0]);
					
					if (val1) {
						var value = date('d.m.Y', val1);
					}
					else {
						var value = date('d.m.Y', Math.max(val1, val2));
					}
					
					$('departure').set('value',value);
					init_tooltip();
				}
			}).post({
				mod: 'getCalendar',
				year: year_d,
				month: month_d,
				field: 'calendar-marker-departure',
				persons: persons,
				rooms: rooms,
				idShelter: idShelter,
				arrival: arrival,
				departure: departure
			});
		}
		$$('.error').destroy();
	}
}

window.addEvent('domready', function() {

	init_navigation();
	init_tooltip();

	if ($$('.mbox').length) {
		
		var initMultiBox = new multiBox({
			mbClass: '.mbox',
			container: $(document.body),
			useOverlay: true,
			addRollover: false,
			addOverlayIcon: false,
			addChain: false,
			recalcTop: false,
			path: 'http://www.urlaub-mitten-in-deutschland.de/fileadmin/video/multiBox2.0.2/Files/',
			addTips: true
		});
	}

	if ($('SlideItMoo_banners_outer')) {
		new SlideItMoo({
			overallContainer: 'SlideItMoo_banners_outer',
			elementScrolled: 'SlideItMoo_banners_inner',
			thumbsContainer: 'SlideItMoo_banners_items',
			itemsVisible: 1,
			itemsSelector: '.banner',
			showControls: 0,
			autoSlide: 3000,
			transition: Fx.Transitions.Cubic.easeInOut,
			duration: 1800,
			direction: 1
		});

	}

	if ($$('.demo_vista').length) {
		new DatePicker('.demo_vista', {
			inputOutputFormat: 'd.m.Y',
			format: 'd.m.Y',
			pickerClass: 'datepicker_vista',
			days: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
			months: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']
		});
	}
	/*var tabs = new SimpleTabs('demo-block', {selector: 'h4'});*/

	/** Player ausschalten */
	if ($('player')) {
		$('player').addEvent('click', function(e){

			var myCookie = Cookie.read('mute');
			var val = myCookie == 1 ? 0 : 1;
			Cookie.write('mute', val, {
				duration: 1
			});

		})
	}

	/** Anbieterregistrierung */
	if($('register_4')){

		$('register_4').addEvent('keyup', function(e){
			var plz = this.get('value');
			if(plz.match(/^\d{1,5}$/)){
				if(plz.length == 5){
					$('register_5').setStyle('backgroundColor','#cdcdcd');
					var req = new Request.HTML({
								url:'fileadmin/php/registrieren_anbieter.php',
								onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
												$('register_5').getParent().set('html',responseHTML);
											},
								update: $('register_5')
								}).post({mod:'getCities',zip:plz});

				}
			}else{
				var substr = plz.substring(0,plz.length-1);
				this.set('value',substr);
			}

		})
	}

	/** Veranstaltungseintragung */
	if($('newevent_6')){

		initNXGMap(document.getElementById('mapid'));
		init_citycrawler();
		init_zipcrawler();

	}else if($('coordX') && $('coordY')){
		initNXGMap(document.getElementById('mapid'));
		var lat = $('coordX').get('value');
		var lon = $('coordY').get('value');
		var search = lat+','+lon;
		showAddress(search,'',true);
	}

	if ($('demo-block')) {
		var tabs = new SimpleTabs('demo-block', {
			selector: 'h4'
		});
	}

	/** Merkliste Eintrag entfernen */
	$$('.delfromlist').addEvent('click',function(e){
		e.preventDefault();
		var delid = this.get('id');
		var deltt = delid.split('-')[0];
		var delid = delid.split('[')[1].split(']')[0];

		var search = ['[',']','{','}','"'];
		var replace = ['','','','',''];
		var myCookie = Cookie.read('tt_news_merker');
		myCookie = str_replace(search,replace,myCookie);
		var cookfield = myCookie.split('-');

		var newCookie = '{';
		for(i=0;i<cookfield.length;i++)
		{
			if (cookfield[i]) {
				var cookspot = cookfield[i].split(':');
				var tt = cookspot[0];
				var ids = cookspot[1].split(',');
				for (j = 0; j < ids.length; j++)
				{
					var id = ids[j];
					if (id) {
						if (deltt != tt || delid != id) {
							if(newCookie.match('"-'+tt+'":')){
								newCookie += ',"'+id+'"';
							} else{
								newCookie += '"-'+tt+'":["'+id+'"';
							}
						}
					}
					if(j == ids.length-1 && newCookie != '{' ){
						if (i < cookfield.length - 1) {
							newCookie += '],';
						}else{
							newCookie += ']';
						}
					}
				}
			}
		}
		newCookie += '}';
		Cookie.write('tt_news_merker', newCookie);
		location.reload();
	})

	$$('#packlist a').addEvent('click',function(e){
		e.preventDefault();
		var href = this.get('href').replace('fileadmin/php/','');
		//alert(href);
		top.location.href = 'http://www.urlaub-mitten-in-deutschland.de' + href;
	})

	$$('.stateselector').addEvent('click',function(e){
		var id = this.get('Id');
		new Element("div", {id: "loading"}).inject($('calendar-marker'));
		var req = new Request.HTML({
						url:'fileadmin/php/holidays.php',
						onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
										$('calendar-marker').set('html',responseHTML);
										init_tooltip();
									},
						update: $('calendar-marker')
						}).post({mod:'getHolidays',id:id});

	})



	if($('dropAccount_2')){
		$('dropAccount_2').addEvent('click',function(e){
			if(!confirm("Achtung!\nSie sind dabei Ihr Benutzerkonto zu löschen.\n\nAlle Daten und Verweise werden unwideruflich entfernt.\n\nWirklich fortsetzen?")){
				e.preventDefault();
			}
		})
	}

	/** Kalenderneuberechnung bei Eingabeänderung */
	if($('erwachsene')){

		if($('zimmer')){
			$('zimmer').addEvent('keyup',function(e){
				if(parseInt($('erwachsene').get('value'),10) < parseInt($('zimmer').get('value'),10)){
					$('erwachsene').set('value',$('zimmer').get('value'));
				}	
			})
		}

		$('data').addLiveEvent('keyup','input',function(e){
			init_checkup();
		})
		$('data').addLiveEvent('change','select',function(e){
			init_checkup();
		})

	}

	if($('schnellsuche')){
		$$('#schnellsuche .selectone').addEvent('change',function(e){
			var current_id = this.get('id');
			$$('.selectone').each(function(element){
				if(current_id !== element.get('id')){
					element.set('value',-1);
				}
			})
		})
	}	

	/* Start Bildergalerie */
	if($('stage')){
		
		var loop = 1;
		var timer = 5000;
		
		function fadeStage(id)
		{
			/* Images */
			if ($$('.stagepicture.last_active').length) {
				//var beforelast = $$('.stagepicture.last_active')[0];
				$$('.stagepicture').setStyle('opacity', 0);
				$$('.stagepicture.active').setStyle('opacity', 1);
				$$('.stagepicture').removeClass('last_active');
			}
			
			var last = $$('.stagepicture.active')[0];
			last.removeClass('active');
			last.addClass('last_active');	
	
			var current = $('stagepicture-'+id);
			current.addClass('active');			
			
			/* Fadeeffect */
			var myFx = new Fx.Tween('stagepicture-'+id,{duration:Math.max(2000,timer/3)});
			myFx.start('opacity','0','1');
			
			/* Tabs */
			$$('.actor').removeClass('active');
			$('act-'+id).addClass('active');
		}
				
		function loadStage()
		{
			if(loop == $$('.actor').length) loop = 0;
			fadeStage(loop);
			loop++;					
			myTimer = loadStage.delay(timer);
		}
		
		$$('.stagepicture').setStyle('opacity',0);
		$('stagepicture-0').setStyle('opacity',1);
		if(timer) var myTimer = loadStage.delay(timer);				
		
		$('stagenavbar').addLiveEvent('click','.actor',function(e){
			if (!this.hasClass('active')) {
				var id = this.get('id').split('-')[1];				
				fadeStage(id);				
				loop = parseInt(id, 10) + 1;				
				if (timer) {
					myTimer = $clear(myTimer);
					myTimer = loadStage.delay(timer * 3);
				}
			}	
		})
	}
	
	if($('filter-sort')){
		$('filter-sort').addEvent('change',function(e){			
			var url = location.href;
			var sort = this.get('value');
			var new_url = url.match(/sort/) ? url.replace(/&sort=\d+/,'&sort='+sort) : url+'&sort='+sort;
			//console.log(new_url);
			location.href = new_url;
		})
	}
})
