// debug
if (typeof console == "undefined") {
    console = {
        log: function (v) {
        }
    };
}


function gotoLink (htmlElement) {

	var destinationURL = "";
	var target = "";

	if ( htmlElement.href ) {
		destinationURL = htmlElement.href;
		target = htmlElement.getAttribute("target");
	}
	else {
		if ( htmlElement.childNodes ) {
			if( htmlElement.getElementsByTagName("a") ) {
				destinationURL = htmlElement.getElementsByTagName("a")[0].href;
				target = htmlElement.getElementsByTagName("a")[0].getAttribute("target");
			}
		}
	}

	if ( destinationURL.length > 0 ) {
		if( target == "_blank" ) {
			window.open(destinationURL);
		}
		else {
			location.href = destinationURL;
		}
	}
	return false;
};


jQuery.fn.zoom = function(fn) {
	jQuery(document).keydown(function(e){
		switch (true) {
			case jQuery.browser.mozilla || jQuery.browser.msie :
				if (e.ctrlKey && (
					e.which == 187 || // =/+ (zoom in [FF, IE])
					e.which == 189 || // -   (zoom out [FF, IE])
					e.which == 107 || // +   (numpad) (zoom in [FF, IE])
					e.which == 109 || // -   (numpad) (zoom out [FF, IE])
					e.which == 96  || // 0   (reset zoom [FF, IE])
					e.which == 48     // 0   (numpad) (reset zoom [IE, FF, Opera])
				)) fn();
				break;
			case jQuery.browser.opera :
				// Opera requires CTRL to be pressed for reset (using num 0)
				if (
					e.which == 43 ||             // +   (numpad) (zoom in [Opera, Safari])
					e.which == 45 ||             // -   (numpad) (zoom out [Opera, Safari])
					e.which == 42 ||             // *   (numpad) (reset zoom [Opera])
					(e.ctrlKey && e.which == 48) // 0   (numpad) (reset zoom [FF, IE, Opera])
				) fn();
				break;
			case jQuery.browser.safari :
				// Use e.metaKey for the Apple key
				if (e.metaKey && (
					e.charCode == 43 || // +   (numpad) (zoom in [Opera, Safari])
					e.charCode == 45    // -   (numpad) (zoom out [Opera, Safari])
				)) fn();
				break;
		}
		return;
	});

	// Set handler for scrollwheel zooming in IE
	jQuery(document).bind('mousewheel', function(e){
		if (e.ctrlKey) fn();
	});

	// Set handler for scrollwheel zooming in Firefox
	jQuery(document).bind('DOMMouseScroll', function(e){
		if (e.ctrlKey) fn();
	});
};


function startflowplayer (uniqid, url, iosUrl, width, height) {
	

	$("#" + uniqid).width(width).height(height);
	
	flowplayer(uniqid, "/static/swf/flowplayer-3.2.7.swf", {
		clip:  {
			autoPlay: true,
			autoBuffering: true,
			url: url,
            ipadUrl: iosUrl
		},
		play: {
			label: null
		},
		plugins: {
			controls:  {
				backgroundColor: 'rgba(0, 0, 0, 0.3)',
				backgroundGradient: 'none',
				bottom: '0.1',
				all: false,
				scrubber: true,
				mute: true,
				volume: true,
				play: true,
				stop: false,
				time: true,
				height: 34,
				progressColor: '#b3dcf4',
				bufferColor: '#333333',
				autoHide: true
			}
		},
		onLoad: function() {
			this.setVolume(30);
		}
	}).ipad();
}


function toolTip(poi,jsppane) {

	var poipos_left = $(poi).position().left;  // Position from parent element left
	var poipos_top = $(poi).position().top; // Position from parent element top
	var poipos_vp_left = $(poi).offset().left; // Position from left viewport
	var poipos_vp_top = $(poi).offset().top; // Position from top viewport
	var window_h_size = $(window).width(); // Window width
	var window_v_size = $(window).height(); // Window height
	var cont_h_size = $(poi).parent().width(); // Parent Container Width
	var cont_v_size = $(poi).parent().height(); // Parent Container Height
	var poi_id = $(poi).attr("class"); // Class of the POI
	var poi_id = poi_id.split(" "); // 
	var poi_id = poi_id[1]; // 


	if ( $(jsppane).length > 0  ) {
		var jcont_h_size = $(jsppane).width(); // JspPane Width
		var curr_a_width = $(poi).width();
		var jcont_v_size = 425; // Height of the parent element
		
		var jx_width = poipos_left + 400; // Position from parent element left + item_width
		$(poi).css("z-index","auto");
		
	}

	var x_width = poipos_vp_left + 400; 
	var curr_tt = $(".tooltip." + poi_id);

	$(poi,"#listbutton").css("z-index","100");
	$(curr_tt).clone().appendTo(poi);

	var curr_height = $(".tooltip",poi).height();
	var y_height = poipos_vp_top + curr_height;
	var y_height_cont = poipos_top + curr_height; // Position from parent element top + item_height
	
	if ( $(jsppane).length > 0 ) {
		if (jx_width > jcont_h_size) {
			$(".tooltip",poi).css("left","auto").addClass("left");
			if (y_height_cont > jcont_v_size) {	// 
				$(".tooltip",poi).addClass("bottom");
			}
		}
		if (y_height_cont > jcont_v_size) {
			$(".tooltip",poi).addClass("bottom");
			if (jx_width > jcont_h_size) {
				$(".tooltip",poi).css("left","auto").addClass("left");
			}
		}
	}
		
	else {
		if ( (x_width > window_h_size) || (jcont_h_size > cont_h_size) ) {
			$(".tooltip", poi).addClass("left");
		}
		if ( (y_height > window_v_size) || (y_height_cont > cont_v_size) ) {
			$(".tooltip", poi).addClass("bottom");
		}
	}

}


function deleteModulesFromSession(code) {
	var ajaxRequestDeleteModules = $.ajax({
		data: {countrycode: code, deletemodules: true},
		type: "GET",
		cache: false,
		dataType: 'json',
		url: '/dmc/modulessession',
		timeout: 2500,
		success: function(json){
			if (ajaxRequestDeleteModules.status == 200){	
				//window.location.href = $(clickedlink).attr("href");
			}
		}
	});
}


$(document).ready(function() {


	// FOOTER RESIZING

	if ( $("#footerarea.resizeme").length > 0 ) {
		$("#footerarea.resizeme").height(105);
		var windowheight = $(window).height();
		var bodyheight = $("body").height();
		var difference = windowheight - bodyheight;
		if (difference >= 0) {
			$("#footerarea.resizeme").height(105 + difference);
		}

		$(window).resize(function() {
			$("#footerarea.resizeme").height(105);
			var windowheight = $(window).height();
			var bodyheight = $("body").height();
			var difference = windowheight - bodyheight;
			if (difference >= 0) {
				$("#footerarea.resizeme").height(105 + difference);
			}
		});

	}

	// RIGHTCOL.MAP .TITLE SPAN HEIGHT

	if ( $(".rightcol.map .title span").length > 0 ) {
		var rcheight = $(".rightcol.map .title span").height();
		if ( rcheight > 20 ) {
			$(".rightcol.map .title span").css("padding","20px 0 0 0");
		}
	}
	
	// SWAP VALUE
	
	if($(".swapvalue").length > 0) {
        var swap_val = [];
        $(".swapvalue").each(function(i){
            swap_val[i] = $(".standardvalue", $(this).parent()).text();
            $(this).focusin(function(){
                if ($(this).val() == swap_val[i]) {
                    $(this).val("");
                }
            }).focusout(function(){
                if ($.trim($(this).val()) == "") {
                    $(this).val(swap_val[i]);
                }
            });
        });
    }
	
	// DATEPICKER
	
	if( $("input.date").length > 0 ) {
		/* German initialisation for the jQuery UI date picker plugin. */
		jQuery(function($){
			$.datepicker.regional['de'] = {
				closeText: 'schlie&szlig;en',
				prevText: '&#x3c; zur&uuml;ck',
				nextText: 'vor &#x3e;',
				currentText: 'heute',
				monthNames: ['Januar','Februar','M&auml;rz','April','Mai','Juni',
				'Juli','August','September','Oktober','November','Dezember'],
				monthNamesShort: ['Jan','Feb','M&auml;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']);
		});

		$.datepicker.setDefaults($.datepicker.regional[""]);
		if(lang == "de") {
			$("input.date").datepicker($.datepicker.regional["de"]);
		} else {
			$("input.date").datepicker($.datepicker.regional[""]);
		}
	}
	
	if( $("input.requestdate").length > 0 ) {
		/* German initialisation for the jQuery UI date picker plugin. */
		jQuery(function($){
			$.datepicker.regional['de'] = {
				closeText: 'schlie&szlig;en',
				prevText: '&#x3c; zur&uuml;ck',
				nextText: 'vor &#x3e;',
				currentText: 'heute',
				monthNames: ['Januar','Februar','M&auml;rz','April','Mai','Juni',
				'Juli','August','September','Oktober','November','Dezember'],
				monthNamesShort: ['Jan','Feb','M&auml;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: '',
				minDate: 0};	
			$.datepicker.setDefaults($.datepicker.regional['de']);
		});

		$.datepicker.setDefaults($.datepicker.regional[""]);
		if(lang == "de") {
			$("input.requestdate").datepicker($.datepicker.regional["de"]);
		} else {
			$("input.requestdate").datepicker($.datepicker.regional[""]);
		}
	}
	
	
	if( $("input.requestdate").length > 0 ) {
		var arrivaldate = $("input.requestdate[name='arrivaldate']");
		var departuredate = $("input.requestdate[name='departuredate']");
		
		var arrivaldateval = 0;
		var departuredateval = 0;
		
		$("input.requestdate").change(function() {
			
			if($(this).val().length > 0) {
				
				if(arrivaldate.datepicker('getDate') > departuredate.datepicker('getDate')) {
					if($(this).attr("name") == "arrivaldate" || $(this).attr("name") == "departuredate") {
						var dateRangeDays = 1;
						if($(this).attr("name") == "departuredate") {
							var dateRangeDays = -1;
						}
		
						var d = new Date($(this).datepicker('getDate'));
						d.setDate(d.getDate() + dateRangeDays);
						curr_date = d.getDate();
						if (curr_date < 10) {
							curr_date = '0' + curr_date
						}
						var curr_month = d.getMonth() + 1;
						if (curr_month < 10) {
							curr_month = '0' + curr_month
						}
						var curr_year = d.getFullYear();
						
						if ( lang == "de" ) {
							if($(this).attr("name") == "departuredate") {
								arrivaldate.val(curr_date + '.' + curr_month + '.' + curr_year);
							} else {
								departuredate.val(curr_date + '.' + curr_month + '.' + curr_year);
								//departuredate.datepicker('setDate', $.datepicker.parseDate('dd.mm.yy', curr_date + '.' + curr_month + '.' + curr_year));
							}
						} else {
							if($(this).attr("name") == "departuredate") {
								arrivaldate.val(curr_year + '-' + curr_month + '-' + curr_date);
							} else {
								departuredate.val(curr_year + '-' + curr_month + '-' + curr_date);
								//departuredate.datepicker('setDate', $.datepicker.parseDate('mm/dd/yy', curr_year + '-' + curr_month + '-' + curr_date));
							}
						}
					}
				}
	
				if(lang == "de") {
					arrivaldateArr = arrivaldate.val().split(".");
					departuredateArr = departuredate.val().split(".");
					
					if (arrivaldateArr.length == 3 && departuredateArr.length == 3) {
						arrivaldateval = $.datepicker.parseDate('dd.mm.yy', arrivaldate.val());
						departuredateval = $.datepicker.parseDate('dd.mm.yy', departuredate.val());
						
						difference = departuredateval - arrivaldateval;
	
						nights = 0;
						
						if(difference >= 0) {
							nights = Math.round(difference/1000/60/60/24);
							
							$("span.nights").text(nights);
							$("span.days").text(nights+1);
							
							$("input[name='nights']").val(nights);
							$("input[name='days']").val(nights+1);
						} else {
							$("span.nights").text(0);
							$("span.days").text(0);
							
							$("input[name='nights']").val(0);
							$("input[name='days']").val(0);
						}
					}
					
				} else {
					arrivaldateArr = arrivaldate.val().split("/");
					departuredateArr = departuredate.val().split("/");
					
					if(arrivaldateArr.length == 3 && departuredateArr.length == 3) {
						arrivaldateval = $.datepicker.parseDate('mm/dd/yy', arrivaldate.val());
						departuredateval = $.datepicker.parseDate('mm/dd/yy', departuredate.val());
						
						difference = departuredateval - arrivaldateval;
						
						nights = 0;
						
						if(difference >= 0) {
							nights = Math.round(difference/1000/60/60/24);
							
							$("span.nights").text(nights);
							$("span.days").text(nights+1);
							
							$("input[name='nights']").val(nights);
							$("input[name='days']").val(nights+1);
						} else {
							$("span.nights").text(0);
							$("span.days").text(0);
							
							$("input[name='nights']").val(0);
							$("input[name='days']").val(0);
						}
					}
				}
			
			}
			
		});
	}

	// MAP

	if ( $("#contentarea.map").length > 0 ) {

		var poicount = $("a.poi", "#contentarea").length;

		// Set POI Position

		for (i=0; i<poicount; i++) {
			var coords = $("a.poi:eq("+i+")","#contentarea").attr("rel");
			var parts = coords.split(",");
			$("a.poi:eq("+i+")","#contentarea").css("left",parts[0]+"px").css("top",parts[1]+"px");
		}

		// Show and Hide List View

		$("#listbutton a.button").click(function() {
			$("#list").removeClass("isnone");
			$(".scrollme:first","#list").jScrollPane({
				verticalDragMinHeight	:	65,
				verticalDragMaxHeight	:	65
			});
			return false;
		});
		
		$("#list a.close").click(function() {
			$(".tooltip","#list").remove();
			$("#list").addClass("isnone");
			return false;
		});

	}

	// TOOLTIPS

	if ( $("#tooltips").length > 0 ) {	
	
		$("a.poi").live({
			mouseenter:
				function()
					{
						toolTip(this);
						/*var thistoolTip = $(".scrollme", this).jScrollPane({
							verticalDragMinHeight	:	65,
							verticalDragMaxHeight	:	65
						});*/
					},
			mouseleave:
				function()
					{
						$(this).empty().css("z-index","3");
					}
			}
		);
	
		
		

		$("#list").not(".tooltip").click(function() {
			$(".tooltip","#list").remove();
			$("span.poi",".jspPane").css("z-index","14");
		});


		$("ul li span.poi",".jspPane").live("click",function() {
			$(".tooltip","#list").remove();
			toolTip(this,".jspPane");
			/*var thistoolTip = $(".scrollme", this).jScrollPane({
				verticalDragMinHeight	:	65,
				verticalDragMaxHeight	:	65
			});*/
			
			$(".scrollme",this).click(function(e) {
				return false;
			});
		});




	}

	// BACKSTRETCH & CONTENT HEIGHT

	if ( portal == true ) {

		var theWindow = $(window);
		var $ca_portal = $("#contentarea");
		var headerheight = $("#headerarea").height();
		var footerheight = $("#footerarea").height();
		var contentheight = theWindow.height() - headerheight - footerheight;
		// $ca_portal.height(contentheight);

		$(window).resize(function() {
						
			var $ca_portal = $("#contentarea");
			var headerheight = $("#headerarea").height();
			var footerheight = $("#footerarea").height();
			var contentheight = theWindow.height() - headerheight - footerheight;
			//$ca_portal.height(contentheight);

		});

		if ( ie6 == false ) {
			if ( backgroundimage.length > 0 ) {
				$.backstretch(backgroundimage);
			}
		}
		if ( ie6 == true ) {
			var ie6bg = "#1a171b url(" + backgroundimage + ") top center no-repeat !important";
			$("body").css("background",ie6bg);
		}

	}

	// DRAG & DROP

	if ( $("ul#sortable").length > 0 ) {

		$(function() {
				   
			var modulescroll = $("#modulecontainer").jScrollPane({
				verticalDragMinHeight	:	65,
				verticalDragMaxHeight	:	65
			}).bind( 'jsp-scroll-y', function(){
			   $(this).trigger('scroll');
			});
			
			var modulescrollapi = modulescroll.data('jsp');

			modulescroll.scroll(function() {
				$(".tooltip").hide();
			});
			
			// to prevent the chrome scrollbar-offset bug for sortable, add class makejourny to contentarea with position: static
			
			if ( $(".limitcontainer.modules").length ) {
				$("#contentarea").addClass("makejourney");
			}
			
			
			// define basic variables

			var $sortable = $("ul#sortable"),
				$modulesul = $("ul#modules"),
				$smodulesul = $("ul#smodules");

			// module sortable

				$modulesul.sortable({
					helper: "clone",
					containment: "#contentarea",
					appendTo: "#contentarea",
					connectWith: 'ul#sortable',
					create: function(event, ui) {
					},
					start:  function(event, ui) {
						$(ui.helper).addClass("helper");
						$(".howto").removeClass("isnone");
						$("#modulecontainer").hide();
						$(".tooltip").hide();
						/*$(".jspPane","#modulecontainer").css("height","0px");
						$("ul#modules",".limitcontainer.modules").hide();
						$("ul#modules li",".limitcontainer.modules").hide();*/
					},
					receive  :   function(event,ui) {
						/*$("a.delete",$sortable).removeClass("isnone");
						$("a.choose",$sortable).addClass("isnone");*/
					},
					stop	:	function(event,ui) {
						$(".howto").addClass("isnone");
						$("#modulecontainer").show();
						/*$("ul#modules",".limitcontainer.modules").css("height","auto").css("overflow","visible");*/
						/*$(".jspPane","#modulecontainer").css("height","auto");
						$("ul#modules",".limitcontainer.modules").show();
						$("ul#modules li",".limitcontainer.modules").show();*/
					}
				});
				$modulesul.disableSelection();

			// standard module sortable

				$("li",$smodulesul).draggable({
					helper: "clone",
					containment: "#contentarea",
					appendTo: "#contentarea",
					connectToSortable: 'ul#sortable',
					start: function(event, ui) {
						$("#modulecontainer").hide();
					},
					stop	:	function(event,ui) {
						$("#modulecontainer").show();
					}

				});

			/* timeline sortable */

				var timelinewidth;
				var triangleCoords = [];
				$sortable.sortable({
					helper: "clone",
					axis: "x",
					containment: $sortable,
					connectWith: "#modules ul",
					appendTo: $sortable,
					receive  :   function(event,ui) { // item is dropped
						$("a.deletestandard",$sortable).removeClass("isnone");
						refreshPolygons();
						countData();
						refreshDays();
						TotalLength();
						modulescrollapi.scrollToY(0);
						updateTLScrollpane();
						//modulescrollapi.reinitialise();
						
						$("li","ul#modules.ui-sortable").fadeIn("fast");
						
						// saveModulesToSession();
						//console.log("dropped from modulelist / standardlist");
					},
					stop: function(event,ui) { // Sorting has stopped
						refreshPolygons();
						refreshDays();
						TotalLength();
						modulescrollapi.scrollToY(0);
						//modulescrollapi.reinitialise();
						
						// saveModulesToSession();
						//console.log("timeline sorting stopped");
					}
				});
				$sortable.disableSelection();

			// Choose Travel Module

			var timelinewidth = 0;
			var currwidth = 0;
			function deleteImage( $item ) {
				$(".tooltip").hide();
				$item = $item.parent();
				$item.fadeOut(0, function() {
					updateTLScrollpane();
					$item.appendTo( $sortable ).fadeIn(function(){
						var tl_items = $("#timeline ul").children().length;
						var itemswidth = 0;
						for (var i=0; i<tl_items;i++) {
							currwidth = $("#timeline ul li:eq("+i+")").width();
							var currwidth = currwidth + 2;
							itemswidth = itemswidth + currwidth;
						}
						timelinewidth = timelinewidth + itemswidth;
						$("ul#sortable").width(itemswidth);
						updateTLScrollpane();
						countData();
						refreshDays();
						refreshPolygons();
						TotalLength();
						modulescrollapi.scrollToY(0);
						//modulescrollapi.reinitialise();
						
						//console.log("delete custom image");
						
						// saveModulesToSession();
						//console.log("manual choose from modulelist");
					});
				});
			}

			// Choose Standard Module

			function deleteSImage( $item ) {
				$item = $item.parent();
					$item.clone().appendTo( $sortable ).fadeIn(0, function(){
						var tl_items = $("#timeline ul").children().length;
						var itemswidth = 0;
						for (var i=0; i<tl_items;i++) {
							currwidth = $("#timeline ul li:eq("+i+")").width();
							var currwidth = currwidth + 2;
							itemswidth = itemswidth + currwidth;
						}
						timelinewidth = timelinewidth + itemswidth;
						$("ul#sortable").width(itemswidth);
						countData();
						refreshDays();
						updateTLScrollpane();
						
						//console.log("delete standard image");
						
						// saveModulesToSession();
						//console.log("manual choose from standardlist");
					});
			}


			// delete travel item from timeline

			function recycleImage( $item ) {
				var thiskm = $("span.length",$item).text();
				thiskm = parseInt(thiskm);
				var actualkm = $("span.km:eq(0)").text();
				actualkm = parseInt(actualkm);
				var newkm = actualkm - thiskm;
				$("span.km").html(newkm);
				var totaldays = $(".totaltime span.time").text();
				totaldays = parseInt(totaldays);
				var currentdays = $(".daynr",$item).length;
				var newdays = totaldays - currentdays;
				$(".totaltime span.time").empty().html(newdays);
				if ( $item.hasClass("voyage")) {
					var voyagemodules = $(".travelmodules span.modules").text();
					voyagemodules = parseInt(voyagemodules);
					$(".travelmodules span.modules").html(voyagemodules - 1);
					
					$item.fadeOut(function() {
						$item.appendTo( $modulesul ).fadeIn(function() {
							refreshDays();
							refreshPolygons();
							TotalLength();
							modulescrollapi.scrollToY(0);
							//modulescrollapi.reinitialise();
							
							$("a.delete",this).addClass("isnone");
							$("a.choose",this).removeClass("isnone");
							
							// saveModulesToSession();
							//console.log("delete module");
						});
					});
				} else {
					// just remove it
					$item.remove();
				}				
			}

			// what happens when module-choose is clicked

			$( "a.choose", $modulesul ).click(function( event ) {
				var $thisitem = $(this).parent().parent();
				deleteImage( $thisitem );
				
				//console.log("choose custom module");
				
				return false;
			});

			$( "a.choose", "ul#smodules" ).click(function( event ) {
				var $thisitem = $(this);
				deleteSImage( $thisitem );
				
				//console.log("choose standard module");
				
				return false;
			});
			
			$( "a.choose", "#tooltips" ).click(function( event ) {
				var tooltipclass = $(this).parent().parent().attr('class').split(' ').slice(-1);
				var choosebutton = $("#" + tooltipclass);
				
				var $thisitem = $(choosebutton).parent().parent();
				deleteImage( $thisitem );
				return false;
			});

			// delete travel module from timeline

			$( "a.delete" ).click(function( event ) {
				var $thisitem = $( this ).parent().parent().parent();
				recycleImage( $thisitem );
				return false;
			});

			 // delete standard module from timeline

			$("a.deletestandard").live("click",function()  {
				var $item = $(this).parent();
				$(this).parent().fadeOut("",function(){
					$(this).remove();
					refreshDays();
					
					// saveModulesToSession();
					//console.log("delete standard module");
				});

				var standardmodules = $(".standardmodules span.modules").text();
				standardmodules = parseInt(standardmodules);
				standardmodules = standardmodules - 1;
				$(".standardmodules span.modules").html(standardmodules);

				var totaldays = $(".totaltime span.time").text();
				totaldays = parseInt(totaldays);
				var currentdays = $(".daynr",$item).length;
				var newdays = totaldays - currentdays;
				$(".totaltime span.time").empty().html(newdays);
				return false;
			});
			
			$("a.deleteallmodules").click(function( event ) {
				$("li", $sortable).each(function(i) {
					recycleImage( $(this) );
				});
				
				deleteModulesFromSession(countrycode);
				$("#basket .entry." + countrycode + " a.close").click();
				
				return false;
			});

			$("a.saveallmodules").click(function( event ) {
				saveModulesToSession(this);
				return false;
			});
			
			$("a.saveallmodulesandrequest").click(function( event ) {
				saveModulesToSession(this);
				return false;
			});

		});

	}


	// BASKET

	if ( $("#basket").length > 0 ) {
		$("#basket").mouseenter(function() {
			$(".entries",this).removeClass("isnone");
		});
		$("#basket").mouseleave(function() {
			$(".entries",this).addClass("isnone");
		});
		
		var basketcount = $("#basket .entries").children().length;
		$("#basket .count").text("(" + basketcount + ")");
		$("#basket a.close").click(function() {
			$(this).parent().remove();
			basketcount--;
			$("#basket .count").text("(" + basketcount + ")");
		});
	}

	// AUTOCOLUMN

	if ( $(".2col").length > 0 ) {

		/*
	
		var text = $(".2col").text();

		$(".2col").empty();
		$(".2col").html("<div class='col1'></div><div class='col2'></div>");
		
		text = text.replace(/\s{2,}/g, ' ');
		text = text.replace(new RegExp("^[\\s]+", "g"), "");
		text = text.replace(new RegExp("[\\s]+$", "g"), "");
		
		var splittext = text.split(" ");
			
		var half1 = [];
		var half2 = [];
		var lengthCount = 0;
		
		for (var i=0; i<splittext.length; i++) {
			if (lengthCount <= (text.length/2 + 15) ) {
				half1.push(splittext[i]);
			} else {
				half2.push(splittext[i]);
			}
			
			lengthCount += splittext[i].length;
		}
		
		var half1txt = half1.join(" ");
		var half2txt = half2.join(" ");

		$(".col1").text(half1txt);
		$(".col2").text(half2txt);
		
		*/
		
	}

	// GALLERY SLIDER

	if ( $(".gallery.content .slider").length > 0 ) {
		$(".gallery.content .slider").elSlider({
			visibleitems	:	6,
			continuous		:	false
		});

		if ( $(".sl_movingcontainer .sl_item").length <= 6 ) {
			$(".sl_leftarrow, .sl_rightarrow").hide();
		}

		var totalno = $(".gallery .sl_movingcontainer").children().length;
		
		var startno = 1;
		$(".no.current").text(startno);
		$(".no.total").text(totalno);

		$(".sl_item.current").append("<div class='border'></div>");

		// Click on thumbnail

		$(".sl_item").click(function() {
			var link = $("a",this).attr("href");
            var iosLink = $("a",this).attr("rel");
			var thisindex = $(".sl_item").index(this);
			$(".canvas").empty();
			
			if($(this).hasClass("flash")) {
				var uniqid = new Date().getTime();
				$(".canvas").append("<div class='videocontainer' id='player_"+uniqid+"'></div>");
				startflowplayer("player_"+uniqid, link, iosLink, 650, 366);
			} else {
				var thisimg = "<img src='"+link+"' alt='' title='' />";
				$(".canvas").append(thisimg);
			}
			$(".no.current").text(thisindex+1);
			$(".sl_canvas").removeClass("current");
			$(".border",".sl_item").remove();
			$(this).addClass("current");
			$(this).append("<div class='border'></div>");		
			return false;
		});
	}

	// HOTEL GALLERY SLIDER

	if ( $(".gallery.hotel .slider").length > 0  ) {
	
		$(".gallery.hotel .slider").elSlider({
			visibleitems	:	1,
			continuous		:	true,
			animationspeed	:	500,
			autoplay: {
				active: true,
				timeout: 4000,
				callback: function() {
				
					startvalue++;
					displayvalue++;
					
					if ( displayvalue > totalvalue ) {
						displayvalue = 1;
					}
					
					$(".gallery.hotel .no.current").text(displayvalue);
					$(".gallery.hotel .info").hide().delay("500");
					$(".gallery.hotel .info").fadeIn("300");
					
					if (hotelimages.length > startvalue && imagecontainers.eq(startvalue).children().size() == 0 ) {
						imagecontainers.eq(startvalue).append(hotelimages[startvalue]);
					}
					
				}
			}
		});
		
		var startvalue = 1;
		var displayvalue = 1;
		var items = $(".gallery.hotel .sl_movingcontainer").children().length;
		var totalvalue = items;
		var imagecontainers = $(".gallery.hotel .sl_movingcontainer .sl_item .imagecontainer");

		if ( $(".sl_movingcontainer .sl_item").length < 2 ) {
			$(".sl_leftarrow, .sl_rightarrow").hide();
			$(".numbers").hide();
		}
		
		$(".gallery.hotel .no.total").text(items);
		$(".gallery.hotel .no.current").text(startvalue);
		
		$(".gallery.hotel .sl_rightarrow").click(function() {
		
			startvalue++;
			displayvalue++;
			
			if( displayvalue > totalvalue ) {
				displayvalue = 1;
			}
			
			$(".gallery.hotel .no.current").text(displayvalue);
			$(".gallery.hotel .info").hide().delay("500");
			$(".gallery.hotel .info").fadeIn("300");
			
			if ( hotelimages.length > startvalue && imagecontainers.eq(startvalue).children().size() == 0 ) {
				imagecontainers.eq(startvalue).append(hotelimages[startvalue]);
			}
			
			
		});
		
		
		$(".gallery.hotel .sl_leftarrow").click(function() {
			startvalue--;
			displayvalue--;
			if ( startvalue < 1 ) {
				startvalue = totalvalue;
			}
			//console.log(startvalue);
			
			if ( displayvalue < 1 ) {
				displayvalue = totalvalue;
			}
			
			$(".gallery.hotel .no.current").text(displayvalue);
			$(".gallery.hotel .info").hide().delay("500");
			$(".gallery.hotel .info").fadeIn("300");
			
			//if ( hotelimages.length > startvalue && imagecontainers.eq(startvalue).children().size() == 0 ) {
				//console.log(imagecontainers.eq(startvalue));
				imagecontainers.eq(startvalue -1).prepend(hotelimages[startvalue - 1]);
			//}
			
			
				
			/*console.log(hotelimages[startvalue]);*/
			// console.log(displayvalue);
			
		});
		
		$(".buttons a").click(function() {
			$(".buttons a").removeClass("current");
			$(this).addClass("current");
		});
		
		$(".removebox a.button").click(function() {
			$(".buttons a").removeClass("current");
		});
		
		
	}
	
	
	// VIRGIN GALACTIC SLIDER

		if ( $("#contentcontainer.virgin .media .slider").length > 0 ) {

			$("#contentcontainer.virgin .media .slider").elSlider({
				visibleitems	:	6,
				continuous		:	false
			});
		
			$("#contentcontainer.virgin .media .slider").each(function(i) {
				if ($(".sl_movingcontainer .sl_item", this).length <= 6 ) {
					$(".sl_leftarrow, .sl_rightarrow", this).hide();
					$(".sl_visible", this).css("margin", "0");
				}
			});
		

			$(".sl_item.current").append("<div class='border'></div>");

			// Click on thumbnail

			$(".sl_item").live("click", function() {
				var link = $("a",this).attr("href");
                var iosLink = $("a",this).attr("rel");
				var caption = $("img",this).attr("alt");
				var thisindex = $(".sl_item").index(this);				
				$(".canvas").empty();

				$(".gallery .caption .text").text(caption);
				$(".sl_item").removeClass("current");
				$(".border",".sl_item").remove();
				$(this).addClass("current");
				$(this).append("<div class='border'></div>");
				
				if($(this).hasClass("flash")) {
					var uniqid = new Date().getTime();
					$(".canvas").html("<div class='videocontainer' id='player_"+uniqid+"'></div>");
					startflowplayer("player_"+uniqid, link, iosLink, 671, 366);
					//startflowplayer("hallo", link, 671, 366);
				} else {
					var thisimg = "<img src='"+link+"' alt='' title='' />";
					$(".canvas").append(thisimg);
				}
				
				return false;
			});
	}


	// ACCORDION

	if ( $("#accordion").length > 0 ) {
		$("#accordion").accordion({
			autoHeight	:	false,
			collapsible	:	true,
			change: function(event, ui) {
				$("a.ui-accordion-header","#accordion").blur();
			}
		});
	}
	
	
	/* OPEN AGBS IN LIGHTBOX */
	
	if( $(".agbslightbox").length > 0) {
		$(".agbslightbox a").click(function() {
			$.colorbox({/*inline: true, */href: $(this).attr("href"), opacity: 0.2, open: true, width: "600px", height: "70%"});
			return false;
		});
	}
	


	/* GOOGLE MAPS */

	if ( $("#map_canvas").length > 0 ) {
		initialize();
	}

	/* TEASERS PORTAL */

	var t1t1 = $(".first",".teasercontent .one").text();
	var t1t2 = $(".second",".teasercontent .one").text();
	var t2t1 = $(".first",".teasercontent .two").text();
	var t2t2 = $(".second",".teasercontent .two").text();
	var t3t1 = $(".first",".teasercontent .three").text();
	var t3t2 = $(".second",".teasercontent .three").text();

	/* DETAILS TOOLTIP */

	if ( $(".tooltip.details").length > 0 ) {

		$("a.details").click(function() {
		
			var istimetable = false;
			
			if ( $(this).parent().parent().parent().parent().parent().parent().parent().attr("id") == "timeline" ) {
				var istimetable = true;
			}
		
		
			$(".tooltip").hide();		
									  
			var thisid = $(this).attr("id");
			
			//var parentoffset_left = $('#contentcontainer').offset().left;
			//var parentoffset_top = $('#contentcontainer').offset().top;
			var thisoffset_left = $(this).offset().left; // Position from left viewport
			var thisoffset_top = $(this).offset().top; // Position from top viewport
			
			$(".tooltip."+thisid+"").css("left",thisoffset_left + 4);
			$(".tooltip."+thisid+"").css("top",thisoffset_top + 40);
			
			
			if ( istimetable == true ) {
				$(".tooltip."+thisid+"").css("top",thisoffset_top - 350).addClass("arrowbottom").end().find(".button").hide();		
			}
			
			$(".tooltip."+thisid+"").css("display","block");
			
			
			
			return false;
		});
		
		$(".tooltip").mouseleave(function() {
			$(".tooltip").hide().removeClass("arrowbottom");		
			$(".button.choose",".tooltip").show();					   
		});
		
		/*$("#modulecontainer .jspPane").live("click",function() {
			$(".tooltip").hide();
		});*/
		
		

		/*$(".tooltip.details .scrollme").jScrollPane({
			verticalDragMinHeight	:	65,
			verticalDragMaxHeight	:	65
		});*/

		$("a.closett").click(function() {
			$(".tooltip").hide();
			return false;
		});
	}
	
	// ADD SPECIAL CLASS TO "RUNDREISE"-TAB
	
	if ( $("a.tab","#contentheader").length ) {		
		$("a.tab:eq(1)").addClass("round");		
	}
	

});

