$(document).ready(function() {
	$("a.thickbox").colorbox({
		scalePhotos: true, 
		maxWidth: '800px', 
		maxHeight: '640px'
	});
	
	$("a.thickbox.iframe").colorbox({
		iframe: true, 
		width: "650px",
		height: "500px"
	});
	
	$("a.topthickbox").colorbox({
		scalePhotos: true, 
		maxWidth: '500px', 
		maxHeight: '400px'
	});
	
	
	jQuery(".tablesorter").tablesorter();
	
	// if ie6 add pngimage class to all elements 
	// which has a background image, ending on '.png'
	if ($.browser.msie && $.browser.version < 7) {
		$("*").each(function() {
			if ($(this).css("background-image").match(/.*\.png/i)) {
				$(this).addClass("pngimage");
/*				$(this).css("background-position", "right"); */
			}
		});
	}
	
	jQuery.fn.log = function (msg) {
		console.log("%s: %o", msg, this);
		return this;
	};
	
	
/*Calculate Price for Tickets*/
	$.fn.calculatePrice = function() {
		var preis = 0;
		var preis_cent = 0;
		$("#ticketPreisBerechnung input").each(function(){
			if($(this).val() > 0) {
				var anz_tickets = parseInt($(this).val());
				var preis_pro_ticket = parseFloat($(this).parent().find('span.preis_cent').text());
				preis_cent += anz_tickets * preis_pro_ticket;
			}
		});

		preis = parseInt(preis_cent) / 100;

		var num = new NumberFormat();
		num.setInputDecimal('.');
		num.setNumber(parseFloat(preis)); // obj.value is '333.3'
		num.setPlaces('2', true);
		num.setCurrencyValue('$');
		num.setCurrency(false);
		num.setCurrencyPosition(num.LEFT_OUTSIDE);
		num.setNegativeFormat(num.LEFT_DASH);
		num.setNegativeRed(false);
		num.setSeparators(true, '.', ',');
		preis = num.toFormatted();

		$("#ticketSumme").text( preis );
	}
	
	$.fn.validateInput = function() {
		hasError = false;
		
		$("#ticketPreisBerechnung input").each(function() {
			kontingent = parseInt($(this).siblings(".leftContingent").text().replace(/\D*/g, ""),10);
			
			order = parseInt($(this).val());
			if (isNaN(order)) {
				order = 0;
			}
			
			sibling = $(this).parent().parent().siblings().find("input");
			orderSibling = parseInt(sibling.val());
			if (isNaN(orderSibling)) {
				orderSibling = 0;
			}
	
			if (order < 0 || orderSibling < 0 || order + orderSibling > kontingent) {
				$(this).parent().addClass('formError');
				$("#ticketOrderForm a.moreInformation").hide();
				hasError = true;
			} else {
				$(this).parent().removeClass('formError');
				sibling.parent().removeClass('formError');
				
				if (!hasError) {
					$("#ticketOrderForm a.moreInformation").show();
				}
			}
		});
	}
	
	// calculate on first load
	jQuery().calculatePrice();
	
	// validate on first load
	jQuery().validateInput();
	
	$("#ticketPreisBerechnung input").keyup(function(){	
		jQuery().calculatePrice();
		jQuery().validateInput();
	});
	
});