var iv1;
var dates = Array();
$(document).ready(function(){
	
	$.datepicker.regional['de'] = {
			closeText: 'schließen',
			prevText: '&#x3c;zurück',
			nextText: 'Vor&#x3e;',
			currentText: 'heute',
			monthNames: ['Januar','Februar','März','April','Mai','Juni',
			'Juli','August','September','Oktober','November','Dezember'],
			monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
			'Jul','Aug','Sep','Okt','Nov','Dez'],
			dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
			dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			weekHeader: 'Wo',
			dateFormat: 'dd.mm.yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: ''};
		$.datepicker.setDefaults($.datepicker.regional['de']);
	
	
	$(window).scroll(function(){
		clearTimeout(iv1);
		iv1 = setTimeout(scro,200);
	});
	
	$('.price_blk input').click(recalc);
	$('.total').each(recalc);
	
	$('.calendar').datepicker({
		dateFormat:'dd.mm.yy',
		onChangeMonthYear:ocmy,
		onSelect:function(date,it){
			var toan = _toan();
			var up = toan.split('/');
			var f = up.pop();
			f = 'day.'+date+'.'+f.replace(/day\.[0-9]{2}\.[0-9]{2}\.[0-9]{4}\./, '');
			var url = up.join('/')+'/'+f;
			//alert(url);
			document.location.href = url;
		},
		beforeShowDay:function(date){
			// console.log(date);
			var ts = date.getTime();
			if(dates[ts]){
				return [true,''];
			} else {
				return [false,''];
			}
		},
		// changeYear: true,
		firstDay: 1
//		onClose: function(dateText, inst) {
//			resetdtsbyname(inst.id);
//		}
	});
	var co = $.cookie('calendar');
	if(co){
		var d = new Date(parseInt(co));
		var now = new Date();
		if(now.getFullYear()+'_'+now.getMonth() == d.getFullYear()+'_'+d.getMonth()){
			ocmy(now.getFullYear(), now.getMonth()+1);
		} else {
			$('.calendar').datepicker('setDate',d);
		}
	} else {
		var now = new Date();
		ocmy(now.getFullYear(), now.getMonth()+1);
	}
});

function _toan(){
	var toan = document.location.href;
	var ob = $('#calurl');
	if(ob.length){
		toan = ob.val();
	}
	return toan;
}

function recalc(){
	var summ = 3; // vk!
	$('.price_blk').each(function(i, it){
		var price = $('.price', $(it)).html();
		price = parseFloat(price.replace(',','.'));
		var inp = $('input', $(it))[0].checked;
		if(inp){
			summ += price;
		}
	});
	$('.total').html(toPr(summ));
}

function toPr(nr){
	nr = nr.toFixed(2);
	return nr.toString().replace('.', ',');
}

function ocmy(year, month, inst){
	if(inst == undefined){
		inst = {currentDay:new Date().getDate()};
	}
	var d = new Date(year,month-1,inst.currentDay);
	$.cookie('calendar',d.getTime(), {path: '/' });
	var par = {'m':month,'y':year};
	var toan = _toan();
	if(toan.indexOf('veranstaltungen_des_hauses') > 0){
		par.inlh = true;
	}
	$.ajax({
		url:'/programm/ajx_month.html',
		data:par,
		type:'POST',
		success:function(text){
			var j = $.parseJSON(text);
			for(i in j){
				dates[j[i]] = true;
			}
			$('.calendar').datepicker('refresh');
		}
	});
}

var evpo = 0;
function scro(){
	if($(window).height() <= $('.events_calendar').height()){
		return;
	}
	var y = $(document).scrollTop();
	if(evpo == 0){
		evpo = $('.events').position()['top'];
	}
	y = y-evpo+10;
	if(y < 0){
		y = 0;
	}
	$('.events_calendar').stop(true).animate({top:y},1500,'easeOutExpo');
}


/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
