$(document).ready(function() {
	// delete right border on last nav item
	$('#mainnav > li:last').css({border: 'none'});

	$('.tourenimage .thickbox').append("<span class='magnify'></span>");

	// make some images movable in their container (Amtrak)
	makeDraggable();

	// care about the gallery
	if ($('div#gallery').length) { 
		$.getScript("/js/jquery.galleria.js");
	}
	
	// care about the shortlists
	if ($('#shortlistcontainer').length) {
		if ($('#shortlistcontainer h2').length) {
			var headline = '<h2>' + $('#shortlistcontainer h2').text() + '</h2>';
		} else {
			var headline = '';
		}
		var params = $('#shortlistcontainer p a').attr('href');
		params = params.split('?')[1]
		var shortlist = 'tourlist.php?ajax=1&contentonly=1&' + params;
		var morelink = '<p class="morelink"><a href="reisen.php?' + params + '">Alle Angebote anzeigen</a></p>'
		$('#shortlistcontainer').load(shortlist, function() {
			$('#tourlist li:last').css({border: 'none'});
			$('#shortlistcontainer').prepend(headline);
			$('#shortlistcontainer').append(morelink);
		});
	}

	// care about the boxoffers
	if ($('#boxoffers').length) {
		scope = $('#boxoffers').text();
		var boxoffer = '/main/boxoffers.php?ajax=1&scope=' + scope;
		$('#boxoffers').load(boxoffer, function() {
			boxofferLink();
			$('#boxoffers').fadeIn(1500, boxofferTurnPage);
		});
	}
	
	// care about the collapsables
	if ($('.collapsable').length) {
		handleCollapsables();
	}
	
	// care about info boxes
	if ($('.infohead').length) {
		handleInfoboxes();
	}
	
	// care about pricetables (tours)
	if ($('.tourprices').length) {
		// handleTourprices();
	}
	
	// hide items that should only be shown to non-js users
	$('.nojs').hide();
	
	$("#360link a").click(function() {
		var url = $(this).attr('href');
		window.open(url, '360-Grad-Ansicht', 'top=0,left=0,screenX=0,screenY=0');
		return false;
	});
	
	// new vehicle descriptions
	if ($('#companylist').length || $('.vehicledetails').length) {
		$('.vehicleslist a').click(function() {
			showVehicleDetails(this);
			return false;
		});
		// console.debug('bis hier');
	}
	
	// gallery in vehicle descriptions
	$('.vehiclegallery img.thumbnail').live('click', function() {
		switchGalleryPic($(this).attr('src'), $(this).parents('.vehicledetails').attr('id'));
	});
	
	if ($('#switchbox').length) {
		animateSwitchbox();
	}
	
	if ($('#tourcontent').length) {
		buildInternalNav();
		$('#internalnav .ajaxlink, .navlinks .ajaxlink').live('click', function() {
			if ($.browser.msie && $.browser.version < 8) { // fuck ie7
				return;
			}
			switchContent(this);
			return false;
		});
	}

});

function switchContent(e) {
	// console.log(e);
	var link = $(e).attr('href');
	var details = $('#detailinfo');
	$.get(link, {'ajax': 'true'}, function(data) {
		details.slideUp(800, function() {
		    details.empty()
			       .append(data);
			if ($(e).hasClass('pricelink')) {
				details.attr('class', 'prices');
			} else if ($(e).hasClass('descriptionlink')) {
				details.attr('class', 'description');
				buildInternalNav();
			} else if ($(e).hasClass('contactlink')) {
				details.attr('class', 'contact');
				$.getScript('/js/jquery.rsv.js');
				$.getScript('/js/forms.js');
				// hide items that should only be shown to non-js users
				$('.nojs').hide();
			}
		}).slideDown(800);
	});
}

function buildInternalNav() {
	var headings = $('.tourtext h3:not(#inclusion h3)'),
		id = $('#tourid').text();
		navitems = '',
		navlist = '';
	$(headings).each(function (i) {
		$(this).attr('id', 'sh-' + i);
		navitems += '<li><a href="#sh-' + i + '">' + $(this).text() + "</a></li>\n";
	});
	navitems += "<li><a class='ajaxlink pricelink' href='reisebeschreibung.php?id=" + id + "&amp;content=prices'>Preise und Termine</a></li>\n";
	navlist = "<ul id='internalnav' class='navlinks'>\n" + navitems + "</ul>\n";
	$('#internalnavholder').replaceWith(navlist);
	
	// and the links back to the top of the page
	var toplink = '<p class="toplink"><a href="#tourcontent" title="zum Seitenanfang springen">nach oben</a></p>';
	$('.tourtext h3:gt(1):not(#inclusion h3)').before(toplink);
	$('.navlinks.floated').before(toplink);
}

function switchGalleryPic(src, container) {
	// care about the image
	src = src.replace(/-120/, '-440');
	var target = $('#' + container).find('p.bigpicture img');
	target.attr('src', src);
	
	// and now for the image comment
	src = src.replace(/-440/, '');
	src = src.replace(/\/pics\/camper_bilder\//, '');
	var href = '/camper/camper-image-comment.php?ajax=true&vehicleid=' + container + '&image=' + src;
	$.get(href, function(data) {
		target.next().next().text(data);
	});

	
	// scroll into view if needed
	var offset = $('#' + container).offset();
	var pos = $(window).scrollTop();
	if ($('#' + container).parents('#cboxLoadedContent').length) {
		$('#cboxLoadedContent').scrollTop(0);
	} else if (offset['top'] < pos) {
		$(window).scrollTop(offset['top']);
	}
}

function showVehicleDetails(obj) {
	var href = $(obj).attr('href') + '&ajax=true';
	var vehicleid = $(obj).attr('rel');
	if (!$(obj).hasClass('active')) {
		$(obj).addClass('active');
		$.get(href, function(data) {
			$(obj).parent().append(data);
			$('#' + vehicleid).slideDown(600);
		});
	} else {
		$('#' + vehicleid).slideUp(400, function() {
			$(obj).removeClass('active');
		});
	}
}

function handleCollapsables() {
	$('.collapsable').addClass('collapsed');
	$('.collapsable h2').click( function() {
		$(this).parent().children('ul').slideToggle(500);
	});
}

function handleTourprices() {
	$('div.collapsabletype3:not(:first)').addClass('collapsed')
		.prev().addClass('collapsed');
	$('div.collapsabletype4:not(:first)').addClass('collapsed')
		.prev().addClass('collapsed');
	$('h4.ptype4, h5.ptype3').click( function() {
		$(this).toggleClass('collapsed')
			.next().slideToggle(500);
	});
}

function handleInfoboxes() {
	$('.infohead').next().hide();
	// $(':not(#bookinghotels, #bookingflights, #bookinginsurance) .infohead').click( function() {
		// $(this).next().slideToggle(500);
	// });
	$('#bookingflights input:checkbox, #bookinghotels input:checkbox, #bookinginsurance input:checkbox').change( function() {
		$(this).next().next().slideToggle(500);
	});
	$('#insurance .infohead').click( function() {
		$(this).next().slideToggle(500);
	});
}

// functions needed for the boxoffer functionality
function boxofferLink() {
	$('#boxofferpager span[class!="announce"]').click(function() {
		var number = parseInt($(this).html());
		boxofferLinkAction(number, scope);
	});
}
function boxofferLinkAction(number, scope) {
	stopTurnPage();
	var boxoffer = '/main/boxoffers.php?ajax=1&number=' + number + '&scope=' + scope;
	$('#boxoffers').fadeTo(500, 0.1, function() {
		$('#boxoffers').load(boxoffer, function() {
			boxofferLink();
			$('#boxoffers').fadeTo(500, 1, boxofferTurnPage);
		});
	});
}
function boxofferTurnPage() {
	var forward = parseInt($('#boxofferpager .forwardlink').html());
	aktiv = window.setTimeout("boxofferLinkAction(" + forward + ", '" + scope + "')", 10000);
}
function stopTurnPage() {
	window.clearTimeout(aktiv);
}

// make some images movable in their container (Amtrak)
function makeDraggable() {
	var image = $(".dragimg img");
	var imgwidth = image.width();
	var imgheight = image.height();
	if (imgwidth == 0 || imgheight == 0) {
		aktiv = window.setTimeout("makeDraggable()", 200);
		return;
	}
	if (imgwidth < 696) {
		$(".dragimg").width(imgwidth);
	}
	if (imgheight < 394) {
		$(".dragimg").height(imgheight);
	}
	if (imgheight > $(".dragimg").innerHeight() || imgwidth > $(".dragimg").innerWidth()) {
		image.draggable()
		                 .css({'cursor': 'move', 'text-align': 'center'});
		$(".dragimg").before('<p style="width: ' + Math.min(imgwidth + 6, 702) + 'px; margin: 0 auto 1em; "><strong>Verschieben Sie den Kartenausschnitt.</strong> Um den Kartenausschnitt zu verschieben, klicken und halten Sie die linke Maustaste gedrückt und verschieben Sie die Karte in die gewünschte Richtung.</p>');
	}
}

// handle switchbox in destination specials
function animateSwitchbox() {
	// build linklist to show next to info box
	var box = $('#switchbox');
	box.addClass('active');
	$('#switchbox div:first-child').addClass('chosen');
	var heads = $('#switchbox h3');
	var subheads = $('#switchbox h4');
	var divs = $('.switchcontent');
	var linklistitems = '';
	$(heads).each(function (i) {
		$(this).parent().attr('id', 'sb-' + i);
		linklistitems += '<li class="sb-' + i + '"><span class="sbhead">' + $(this).text() + '</span><span class="sbsubhead">' + $(subheads[i]).text() + "</span></li>\n";
	});
	var linklist = "<ul id='sblinklist'>\n" + linklistitems + "</ul>\n";
	box.append(linklist);
	$('#sblinklist li:first-child').addClass('chosen');
	
	// listen to clicks on link list
	$('#sblinklist li:not(.chosen)').live('click', function() {
		var id = $(this).attr('class');
		$('#switchbox .chosen').removeClass('chosen');
		$(this).addClass('chosen');
		$('#' + id).addClass('chosen').find('li:first-child').addClass('chosen');
	});
	
	// build list from paragraphs and seperate images
	var ps;
	$(divs).each(function () {
		var imagelistitems = '';
		ps = $(this).children('p');
		// build pager between image and text
		var prev = 0;
		var next = 0;
		var count = $(ps).length;
		var text;
		var prevbutton;
		var nextbutton;
		var control;
		$(ps).each(function (i, el) {
			var img = $(el).children('img').attr('src');
			var alt = $(el).children('img').attr('alt');
			var p = $(el);
			$(p).children('img').remove();
			p = $(p).html();
			// console.log(p);
			if (i == 0) {
				prev = count;
			} else {
				prev = i;
			}
			if (i == count - 1) {
				next = 1;
			} else {
				next = i + 2;
			}
			text = i + 1 + ' von ' + count;
			prevbutton = '<span class="ctrlprev">' + prev + '</span>';
			nextbutton = '<span class="ctrlnext">' + next + '</span>';
			control = '<div class="control">' + prevbutton + text + nextbutton + '</div>';
			// console.log('prev: ' + prev + "\n");
			// console.log('next: ' + next + "\n");
			// console.log('text: ' + text + "\n");
			// console.log('control: ' + control + "\n");
			// console.log(p);
			// console.log(img);
			imagelistitems += i == 0 ? '<li class="chosen"><img src="' + img + '" alt="' + alt + '" />' : '<li><img src="' + img + '" alt="' + alt + '" />';
			imagelistitems += control;
			imagelistitems += '<p>' + p + '</p></li>';
		});
		$(this).append('<ul class="switchlist">' + imagelistitems + '</ul>');
		$(ps).remove();
	});

	// and make pager clickable
	$('span.ctrlprev, span.ctrlnext').live('click', function() {
		$(this).parents('li').removeClass('chosen').parents('ul').children('li:nth-child(' + $(this).text() + ')').addClass('chosen');
		// var name = 'sb-' + $(this).text();
		// $('#switchbox .chosen').removeClass('chosen');
		// $('.' + name).addClass('chosen');
		// $('#' + name).addClass('chosen');
	});


}

function calculateDays(date1, date2) {
	date1 = makeDateFromString(date1);
	date2 = makeDateFromString(date2);
	var d1 = new Date(date1[0], date1[1], date1[2]);
	var d2 = new Date(date2[0], date2[1], date2[2]);
	var diff = d2 - d1 //unit is milliseconds
	return Math.round(diff/1000/60/60/24);
}

function calculateDate(dateText, days) {
	dateText = makeDateFromString(dateText);
	var date = new Date(dateText[0], dateText[1], dateText[2]);
	var olddate = date.getTime();
	var newdate = olddate + days * 24 * 60 * 60 * 1000;
	date.setTime(newdate);
	var theyear = date.getFullYear();
	var themonth = date.getMonth() + 1;
	var thetoday = date.getDate();
	// make month and day a two-digit string
	themonth = themonth < 10 ? '0' + themonth : themonth;
	thetoday = thetoday < 10 ? '0' + thetoday : thetoday;
	var calculated = new Array(
		theyear + '-' + themonth + '-' + thetoday,
		thetoday + '.' + themonth + '.' + theyear
	);
	return calculated;
}

function makeDateFromString(viewdate) {
	var date = viewdate.split('.');
	var month = date[1] - 1;
	var day = date[0];
	var year = date[2];
	return [year, month, day];
}


