var allMonth = [],
	curPidx = 0,
	lastForm = null,
	programMaxHeight = 503;

function decode(utf8){
	try{
		utf8 = decodeURIComponent(utf8);
	}catch(e){
		parts = utf8.split('%20');
		for(var i = 0; i < parts.length; i++){
			try{
				parts[i] = decodeURIComponent(parts[i]);
			}catch(e){
				parts[i] = unescape(parts[i]);
			}
		}
		utf8 = parts.join(' ');
	}
	return utf8;
}

function positionieren(){
	var width = $(window).width(),
		height = $(window).height(),
		pH = 0;
	//$('#program').height('auto');//();
	if(arguments[0]){
		if($('#program').height() > height - 192){
			pH = height - 192;
		}
	}else{
		if($('div.customScrollerContent').length){
			if($('div.customScrollerContent').height() > height - 192){
				pH = height - 192;
			}else{
				pH = $('div.customScrollerContent').height();
			}
		}else{
			if($('#program').height() > height - 192){
				pH = height - 192;
			}
		}
	}
	if(pH){
		$('#program').height( pH > programMaxHeight ? programMaxHeight : pH);
	}
	if(width > 1036){
		$('#kopf').width(width);
		$('#headline').width(width);
	}else{
		$('#kopf').width(1036);
		$('#headline').width(width);
	}
	allHeight(height);

}
function allHeight(height){
	var all = $('#all');
	all.height('auto');
	if(all.height() < height){
		$('#all').height(height);
	}
}
function sendeKontakt(form, event){
	event.preventDefault();
	form.append($('<input type="hidden" name="email" value="'+$()[0]+'"/>'));
	var values = form.serializeArray();
	curForm = form[0];
	$.post(curForm.action, values, showMessage, 'json');
	return false;
}
function showMessage(data){
	var messageWindow = $('<p class="messageWindow">' + data.message + '</p>');
	$('body').append(messageWindow);
	setTimeout(function(){
		messageWindow.remove();
	}, 5000);
}
function showMonth(obj, init){
	$('#program ul.monat.aktiv').removeClass('aktiv');
	if(obj){
		$(obj).addClass('aktiv');
		$('#programMonat')[0].innerHTML = obj.id.replace(/-/,'&nbsp;');
	}
	if(!init){
		$(window).trigger("resize");
	}
}
function linkProgram(anker){
	var parts = anker.id.substr(5).split('_');
	wait();
	$.post('ajax/program_info.php',{program_id:parts[0], datum: parts[1]},
		function(data){
			programInfo(data, parts);
		},'json');
	$('#program a').removeClass('aktiv');

	$('#program #link_'+parts[0]+'_'+parts[1]).addClass('aktiv');
}
function programInfo(data, parts){
	//alert(data.result);
	if(data.result == 'ok'){
		/*if(console.log){
			console.log(unescape(data.html));
		}*/

		$('#inhalt').html(decode(data.html) + (data.teaser ? decode(data.teaser) : ''));
		var big = $('#bigImage')[0],
			last = 0,
			thumbnails = $('.program-image');
		if(thumbnails.size() > 1){
			thumbnails.each(function(idx){
				var img = $(this);
				img.click(function(){
					big.src = this.src;
				}).width(img.width() / 4.3 ).height(img.height() / 4.3 );
			});
		}
		if(thumbnails.size() >= 1){
			big.src = thumbnails[0].src;
		}
		if(thumbnails.size() <= 1){
			thumbnails.remove();
		}
		if($(big).width() > $(big).height()){
			$('.program-text').css('clear','left');
		}

		if($('#program-links p').html() == ''){
			$('#program-links').remove();
		}
		$('#program-tickets').click(function(event){
			event.preventDefault();
			$.post('ajax/program_ticket.php',{program_id:parts[0], datum: parts[1]},
				function(data){
					programTicket(data,parts);
			},'json');
			return false;
		});

		$('#inhalt .startteaser .teaser').each(function(){
			$(this).bind('click', function(e){

				linkProgram(this);

			});
		});

		allHeight($(window).height());
		stopWait();
	}else{
		addWait(data.message);
	}
}
function programTicket(data,parts){
	if(data.result == 'ok'){
		$('#inhalt>*').replaceWith(decodeURIComponent(data.html));
		var	formular = $('#inhalt form');
		if(parts){
			$('input.reset', formular).click(
					function(event){
						event.preventDefault();
						wait();
						$.post('ajax/program_info.php',{program_id:parts[0], datum: parts[1]},
							function(data){
								programInfo(data, parts);
							},'json');
						return false;
					}
			);
		}else{
			$('input.reset', formular).remove();
		}
		$('input.submit', formular).click(
				function(event){
					event.preventDefault();
					wait();
					$.post('ajax/warenkorb_adresse.php',$('#warenkorb').serializeArray(),function(data){
						addressData(data, parts || false);
					},'json');
					return false;
				}
		);
		$('a.delete', formular).click(function(event){
			var id = this.id.split('_').pop(),
				link = this;
			event.preventDefault();
			$.post('ajax/ticket_delete.php', {program_id:id}, function(data){
				$(link).parent().parent().remove();
			},'json');
			return false;
		});
		allHeight($(window).height());
		stopWait();
	}else{
		addWait(data.message);
	}
}
function addressData(data,parts){
	if(data.result == 'ok'){
		$('#inhalt>*').replaceWith(decodeURIComponent(data.html));
		var	formular = $('#inhalt form');
		if($('#fehler-meldungen', formular).html() == ''){
			$('#fehler-meldungen', formular).remove();
		}

		$('input.reset', formular).click(
				function(event){
					event.preventDefault();
					wait();
					$.post('ajax/warenkorb_overview.php',{},
							function(data){
								programTicket(data,parts);
						},'json');
					return false;
				}
		);
		$('input.submit', formular).click(
				function(event){
					event.preventDefault();
					//check todo
					wait();
					$.post('ajax/warenkorb_zusammen.php',formular.serializeArray(),
							function(data){
								bestellung(data);
					},'json');
				}
		);
		allHeight($(window).height());
		stopWait();
	}else{
		addWait(data.message);
	}
}
function bestellung(data){
	if(data.result == 'ok'){
		if(data.failures){
			addressData(data, false);
		}else{
			$('#inhalt>*').replaceWith(unescape(data.html));
			var	formular = $('#inhalt form');
			$('input.reset', formular).click(
					function(event){
						event.preventDefault();
						wait();
						$.post('ajax/warenkorb_adresse.php',{},
								function(data){
									programTicket(data,false);
							},'json');
						return false;
					}
			);
			$('input.submit', formular).click(
					function(event){
						event.preventDefault();
						//check todo
						wait();
						$.post('ajax/bestellung_go.php',formular.serializeArray(),
								function(data){
									abgeschickt(data);
						},'json');
					}
			);
			allHeight($(window).height());
			stopWait();
		}
	}else{
		addWait(data.message);
	}
}
function abgeschickt(data){
	if(data.result == 'ok'){
		if(data.failures){
			data.failures -= 1;
			bestellung(data);
		}else{
			$('#inhalt>*').replaceWith(unescape(data.html));
			if(data.ok){
				$('#warenkorb-preview>*').remove();
			}
			allHeight($(window).height());
			stopWait();
		}
	}else{
		addWait(data.message);
	}
}

function searchResults(data){
	if(data.result == 'ok'){
		$('#inhalt>*').replaceWith(unescape(data.html));
		$('#inhalt a').click(
				function(event){
					event.preventDefault();
					linkProgram(this);
					return false;

		});
		allHeight($(window).height());
		stopWait();
	}else{
		addWait(data.message);
	}
}
function newsletterBestellt(data){
	addWait(decode(data.message));
}
function wait(){
	$('body').append('<div id="wait"/>');
}
function stopWait(){
	$('#wait').remove();
}
function addWait(message){
	$('#wait').css('background-image','url(pix/trans.gif)').click(
			function(){
				$('#wait').remove();
	}).append('<div><p>'+message+'</p></div>');
}

$(document).ready(function(){
	//$(window).bind('resize', positionieren);
	var themes = {},
		domainsShow = false;
	positionieren(true);
	$("#program").customScroller({speed: 4});
	$('#program li').each(
			function(idx,ele){
				var thema = ele.className;
				//alert(ele.className);
				if(!themes[thema]){
					themes[thema] = $('<p class="hbg inaktiv" id="check_'+thema+'"><span class="kasten"></span><span class="label">'+thema+'</span></p>').bind('click',
							function(event){
								var check = this.id.substr(6),
										something = false;
								if($(this).hasClass('inaktiv')){
									$(this).removeClass('inaktiv').addClass('aktiv');
								}else{
									$(this).removeClass('aktiv').addClass('inaktiv');
								}

								for(var theme in themes){
									if(themes[theme].hasClass('aktiv')){
										$('#program li.'+theme).show();
										something = true;
									}else{
										$('#program li.'+theme).hide();
									}
								}

								if(!something){
									$('#program li').show();
								}

								$(window).trigger("resize");
							}

					);
					$('#programfilterBoxes').append(themes[thema]);
				}
			}
	);
	var programShow = false;
	$('#programfilter').click( function(){
			if(!programShow){
				$('#programfilterBoxes').fadeIn('slow');
				programShow = true;
			}
	});
	$('#programfilterBoxes').mouseleave(function(event){
		setTimeout(function(){
			if(programShow){
				$('#programfilterBoxes').fadeOut('slow');
				programShow = false;
			}
		}, 1000);
	}).mouseenter(function(event){
		if(!programShow){
			$('#programfilterBoxes').fadeIn('slow');
		}
		programShow = true;
	});
	$('#programPrevious').bind('click', function(){
		if(--curPidx < 0){
			curPix = 0;
		}else{
			showMonth($('#program ul.monat').get(curPidx));
		}
	});
	$('#programNext').bind('click', function(){
		if(++curPidx >= $('#program ul.monat').length){
			curPidx--;
		}else{
			showMonth($('#program ul.monat').get(curPidx));
		}
	});
	showMonth($('#program ul.monat').get(curPidx), true);
	$('#program a').each(function(){
		$(this).bind('click', function(e){
			e.preventDefault();
			linkProgram(this);
			return false;
		});
	});
	$('#inhalt .startteaser .teaser').each(function(){
		$(this).bind('click', function(e){

			linkProgram(this);

		});
	});
	$('#slides img').each(
			function(idx){
				$(this).bind('click',
						function(event){
							event.preventDefault();
							var img = $('#imageGalerie').children('img')[0];
								orgWidth = $(img).width();
							$(this).replaceWith(img);
							$(img).width($(this).width());
							$(this).width(orgWidth);
							$('#imageGalerie').prepend(this);
							return false;
						}
				);
			}
	);
	$('form.kontakt').bind('submit',function(e){
		sendeKontakt($(this), e);
	});
	$('#searchForm').bind('submit', function(event){
			event.preventDefault();
			wait();
			$.post('ajax/search_results.php',$(this).serializeArray(),
				function(data){
					searchResults(data, false);
			},'json');
			return false;
	});
	$('#warenkorb-preview a').click(
			function(event){
				event.preventDefault();
				wait();
				$.post('ajax/warenkorb_overview.php',{},
						function(data){
							programTicket(data, false);
					},'json');
				return false;
			}
	);

	$('#newsletterDomains p').click(function(event){
		if($(this).hasClass('inaktiv')){
			$(this).removeClass('inaktiv').addClass('aktiv').append('<input type="hidden" name="'+this.id+'" value="1"/>');
		}else{
			$(this).removeClass('aktiv').addClass('inaktiv');
			$('input[type=hidden]', this).remove();
		}
	});
	$('#newsletterForm').mouseleave(function(event){
		domainsShow = false;
		setTimeout(function(){
			if(!domainsShow){
				$('#newsletterDomains').hide();
			}
		}, 1200);
	}).mouseenter(function(event){
		if(!domainsShow){
			$('#newsletterDomains').show();
		}
		domainsShow = true;
	});
	$('#newsletterForm').bind('submit', function(event){
		event.preventDefault();
		$.post('ajax/newsletter_bestellen.php', $(this).serializeArray(), newsletterBestellt, 'json');
		$('#newsletterDomains').hide();
		wait();
		return false;
	});
	if(window.location.search.split('?').length == 2){
		wait();
		addWait(decode(window.location.search.split('?').pop().split('=').pop() ) );
	}

});
