var ajaxCache = true;
var ajaxCache = true;
var DOMReady = false;

if (!teaserOut) {
	var teaserOut;      
}



jQuery(document).ready(function(){
    
    
	DOMReady = true;
	checkSuperBanner();
	//jQuery('input:submit').button();

	// Beim Browser zurück bleibt der alte wert stehen, damit nicht mehr:
	jQuery('.mapcontainer select[name=sort] option[selected=selected]').attr("selected", true);  

	jQuery('#cse-search-box').submit(function(){
		//showLoading();   
		});   
	jQuery('#tx-indexedsearch-searchbox-sword').autocomplete('/index.php',{
		extraParams : {
			'eID'		: 'mg_skiresort_json',
			'action'	: 'quicksearch',
			'l'			: lang
		},			
		parse: function(data) {
			return jQuery.map(data, function(item) {
				return {
					data: item,
					value: item.name,
					result: item.name
				}
			});
		},
		highlight: function(value, term) {
			return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<span class='highlight'>$1</span>");
		},
		formatItem: function(item, i, max) {
//			console.log(item, i, max);
			if (max>0) {
				if (item.type == 'nores') {
					
					$input = jQuery('#tx-indexedsearch-searchbox-sword');
					var offset = $input.offset();
					jQuery('#quicksearchNoRes')
					.appendTo(document.body)
					.css({
						top: offset.top + $input.height() + 2,
						left: offset.left
					})
					.html(item.name).show();
					return false;
				}
				jQuery('#quicksearchNoRes').hide();
				var ad = new Array();
				idx = 0
				c = '';
				c += '<h1><a href="'+item.url+'">'+ item.prefix + ' <span class="highlight">' + item.name+'</span></a></h1>';
				
				if (item.additionalData.region) {
					c +=  '<div class="region">' + item.additionalData.region + '</div>';
				}
				
				if (item.additionalData.cities) {
					c += '<div class="cities">' + item.additionalData.citiesLabel + ' <span class="highlight">' +  item.additionalData.cities + '</span></div>';
				}
				/*
				if (item.additionalData.trailmap) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.trailmapUrl + '\'" href="'+item.additionalData.trailmapUrl+'">'+ item.additionalData.trailmap + '</a>';
				}
				if (item.additionalData.testreport) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.testreportUrl + '\'" href="'+item.additionalData.testreportUrl+'">'+ item.additionalData.testreport + '</a>';
				}
				if (item.additionalData.video) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.videoUrl + '\'" href="'+item.additionalData.videoUrl+'">'+ item.additionalData.video + '</a>';
				}
				if (item.additionalData.snowreport) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.snowreportUrl + '\'" href="'+item.additionalData.snowreportUrl+'">'+ item.additionalData.snowreport + '</a>';
				}
				if (item.additionalData.weather) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.weatherUrl + '\'" href="'+item.additionalData.weatherUrl+'">'+ item.additionalData.weather + '</a>';
				}
				if (item.additionalData.accomodations) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.accomodationsUrl + '\'" href="'+item.additionalData.accomodationsUrl+'">'+ item.additionalData.accomodations + '</a>';
				}
				if (item.additionalData.listBest) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.listBestUrl + '\'" href="'+item.additionalData.listBestUrl+'">'+ item.additionalData.listBest + '</a>';
				}
				if (item.additionalData.listSnowreport) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.listSnowreportUrl + '\'" href="'+item.additionalData.listSnowreportUrl+'">'+ item.additionalData.listSnowreport + '</a>';
				}
				if (item.additionalData.listWeather) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.listWeatherUrl + '\'" href="'+item.additionalData.listWeatherUrl+'">'+ item.additionalData.listWeather + '</a>';
				}
				if (item.additionalData.listAccomodations) {
					ad[idx++] = '<a onclick="location.href=\'' + item.additionalData.listAccomodationsUrl + '\'" href="'+item.additionalData.listAccomodationsUrl+'">'+ item.additionalData.listAccomodations + '</a>';
				}
				
				c +=  ad.join('&nbsp;&nbsp;&nbsp;');
				*/
				return c;
			}
		},
		autoFill:false,
		autoSubmit: false,
		scroll: false,
		width: 400,
		selectFirst: true,
		clickFire: false,
		matchSubset: false,
		delay: 700,
		max: 30
	}).result(function(e, item, formatted) {
		if (!item || item.type == 'nores') {
			return false;
		} else {
			showLoading();
			location.href = item.url;
		}
		
	}).blur(function(){
		jQuery('#quicksearchNoRes').hide();
	});
	
	jQuery('#tx-indexedsearch-searchbox-sword').keydown(function(e){
		if (e.which != 13) {
			jQuery('#quicksearchNoRes').hide();
		}
		if (e.which == 46 ) {
			jQuery('#tx-indexedsearch-searchbox-sword').flushCache();
			jQuery('#tx-indexedsearch-searchbox-sword').search();
		}
	});

	// Karte in Listen nach unten scrollen
	if (jQuery('.mapcontent .listcontainer').length > 0 && defaultMapOffset > 0) {
		jQuery('.mapcontent .listcontainer').scrollTop(defaultMapOffset);
	}



	var pid = jQuery('#resortListFilterForm input[name="pid"]').val() ;
	hideLoading();



	jQuery('#resortListFilterForm input[name="tx_mgskiresort_pi1[resortlist][specialfilter][open]"]').live('click',function(){
		showLoading();

		chk = 0;
		if (jQuery(this).is(':checked')) {
			chk = 1;
		}

		url = jQuery('#resortListFilterForm input[name="filterHref"]').val() + '&type=997';
		setResortlist(url,pid);
		jQuery.ajax({
			type: "GET",
			url: url,
			cache: ajaxCache,
			dataType: "html",

			success: function(response,textStatus){
				var html=jQuery('#resortList',response).html(); 
				jQuery('#resortList').html(html);
				updateContentAferAjaxInList(response);
				hideLoading();
			}
		});

	});




	// *********************************************************



	jQuery('.sortfields a').live('click',function(){
		//return true;
		showLoading(); 
		var clickedElement = this;

		jQuery('.sortfields a').each(function(index){
			if (clickedElement != this) {
				jQuery(this).addClass('init');
			} else {
				jQuery(this).removeClass('init');
			}
		})  ;

		var sort =  jQuery(clickedElement).attr('href');
		var sortDir =  jQuery(clickedElement).attr('class');
		var filter = jQuery('#resortListFilterForm').serialize();
		if (sortDir == 'desc') {
			jQuery(clickedElement).attr("class","asc");
		} else {
			jQuery(clickedElement).attr("class","desc");
		}
		url = jQuery(this).attr('href') + '&type=997';
		setResortlist(url,pid);

		jQuery.ajax({
			type: "GET",
			url: url,
			cache: ajaxCache,
			dataType: "html",
			success: function(response,textStatus){
				var html=jQuery('#resortList',response).html(); 
				jQuery('#resortList').html(html);
				updateContentAferAjaxInList(response);
				hideLoading();
			}
		});
		return false;
	});

	// *********************************************************
	// Vor/Zurück in Resortliste

	jQuery('.pagebrowser a').live('click',function(){
		showLoading();
		return true;
	});




	jQuery.extend({
		searchResort: function(){
			showLoading(); 
			var sword = jQuery('#resortListSearch input[name="tx_mgskiresort_pi1[resortlist][sword]"]').val();
			sword = sword.replace('/','[slash]');
            
			//jQuery.get('ajax');
			ajaxURL = jQuery('#resortListSearch input[name="searchformaction"]').val() + '?&type=997&tx_mgskiresort_pi1[action]=getSearchURL&tx_mgskiresort_pi1[resortlist][sword]='+encodeURIComponent(sword) + '&tx_mgskiresort_pi1[resortlist][sword_h]='+encodeURIComponent(sword);
			jQuery.get(ajaxURL,function(data){
				window.location = data;
			});




		},
		updateSearchInput: function(e) {
			/*
            if (e.val() != searchDefaultVal ) {
            jQuery('#resortListSearch input[name="tx_mgskiresort_pi1[resortlist][sword]"]').val(e.val());
            }
            if (e.val() == ''){
            e.val(searchDefaultVal);
            jQuery('#resortListSearch input[name="tx_mgskiresort_pi1[resortlist][sword]"]').val('');
            }*/
			jQuery('#resortListSearch input[name="tx_mgskiresort_pi1[resortlist][sword]"]').val(e.val());  
			return true;  
		}
	});



	jQuery('.tx-mgskiresort-pi1 .detail .testReport').mouseover(function(){
		jQuery(this).addClass('link');

	}).mouseout(function(){
		jQuery(this).removeClass('link');
	});




	// *********************************************************
	// Tooltip
	jQuery('div.resortDetail a.tooltip').each(function(){
		jQuery(this).qtip({
			show: 'mouseover',
			hide: 'mouseout',
			position: {
				corner: {
					target: 'topLeft',
					tooltip: 'bottomLeft'
				}
			},
			content: {
				url: 'index.php?id=42&type=997&tx_mgskiresort_pi1[action]=getToolTip'  ,
				data: {
					'tx_mgskiresort_pi1[tid]': jQuery(this).attr('id')
				},
				method: 'get'
			},
			style: {   
				name: 'light', 
				tip: 'bottomLeft',
				width: 600,
				border: {
					width: 5,
					radius: 5,
					color: '#CDDCE5'
				} 
			} 
		});    


	});

	jQuery('div.mapcontainer a.tooltip').each(function(){
		jQuery(this).qtip({
			show: 'mouseover',
			hide: 'mouseout',
			position: {
				corner: {
					target: 'bottomLeft',
					tooltip: 'topLeft'
				}
			},
			content: {
				url: 'index.php?id=42&type=997&tx_mgskiresort_pi1[action]=getToolTip'  ,
				data: {
					'tx_mgskiresort_pi1[tid]': jQuery(this).attr('id')
				},
				method: 'get'
			},
			style: {   
				name: 'light', 
				tip: 'topLeft',
				width: 600,
				border: {
					width: 5,
					radius: 5,
					color: '#CDDCE5'
				} 
			} 
		});    


	});

	jQuery('a.tooltipstatic[title]').css('cursor','pointer'); 
	if (!isIFrame) {


		jQuery('a.tooltipstatic[title]').qtip({ 
			hide: 'mouseout',
			position: {
				corner: {
					target: 'bottomLeft',
					tooltip: 'topLeft'
				}
			},
			style: {   
				name: 'light', 
				tip: 'topLeft',
				width: { 
					min: 120 ,
					max: 450
				},
				border: {
					width: 5,
					radius: 5,
					color: '#CDDCE5'
				} 
			}

		});
	} else {
		jQuery('a.tooltipstatic[title]').qtip({ 
			hide: 'mouseout',
			position: {
				corner: {
					target: 'bottomLeft',
					tooltip: 'topLeft'
				}
			},
			style: {   
				name: 'light', 
				tip: 'topLeft',
				width: { 
					min: 120 ,
					max: 300
				},
				border: {
					width: 2,
					radius: 2,
					color: '#D0D0D0'
				} 
			}

		});

	}

	jQuery('.contactFailureForm form input[type=submit]').click(function(){
		jQuery('.contactFailureForm #loadingBg').show();
		jQuery('.contactFailureForm #loading').show();

		jQuery('.contactFailureForm #loading').css('background-image','url(/typo3conf/ext/mg_skiresort/res/img/ajax-loader_contactForm.gif)');

	});
	jQuery('.contactFailureForm form').submit(function() {
		if (jQuery('.contactFailureForm form textarea').val() == '') {
			jQuery('.contactFailureForm #loadingBg').hide();
			jQuery('.contactFailureForm #loading').hide();
			jQuery('label[for=tx_mgskiresort_pi1[desc]]').append('<span style="color:red"><br/ >Dieses Feld darf nicht leer bleiben.</span>');
			jQuery('textarea[name=tx_mgskiresort_pi1[desc]]').css('border','1px solid red');

			return false;          
		}

	});



	jQuery('span.changeDirection a').live('click',function(){
		jQuery('div#directionFormWrapper').toggle(200);
	});



	jQuery('a.showRoute').livequery(function(){
		var el = jQuery(this);

		jQuery(this).fancybox(
		{
			'autoDimensions'    : true,
			'onComplete'        : function() {},
			'onClosed'            : function(){
				tmp = el.attr('href');
				atmp = tmp.split('#');
				id = atmp[1];
				removeMap(id);
			},
			'onStart'            : function() {
				tmp = el.attr('href');
				atmp = tmp.split('#');
				id = atmp[1];
				initMap(id);
			}
		}
		);
	});

	// Slider nur wenn kein AdBlocker an ist
	if ( window.OA_show ) {
		jQuery('.contentcontainerright #slider2, .t3_contentcontainerleft div.right #slider2').anythingSlider({
			width               : 300,        // if resizeContent is false, this is the default width if panel size is not defined
			height              : 260,        // if resizeContent is false, this is the default height if panel size is not defined
			resizeContents      : true,      // If true, solitary images/objects in the panel will expand to fit the viewport
			navigationFormatter : formatSliderText,  // Format navigation labels with text
			navigationLinks     : linkSliderText2,  
			buildArrows            : false,
			autoPlay            : true,
			showStartStop        : false,
			pauseOnHover        : true,
			delay               : 5000,
			animationTime       : 200,
			easing              : "linear"
		});


		jQuery('.t3_contentcontainerleft #slider2').not('.t3_contentcontainerleft div.right #slider2').anythingSlider({
			width               : 504,        // if resizeContent is false, this is the default width if panel size is not defined
			height              : 126,        // if resizeContent is false, this is the default height if panel size is not defined
			resizeContents      : true,      // If true, solitary images/objects in the panel will expand to fit the viewport
			navigationFormatter : formatSliderText,  // Format navigation labels with text
			navigationLinks     : linkSliderText,  // Format navigation labels with text
			buildArrows            : false,
			autoPlay            : true,
			showStartStop        : false,
			pauseOnHover        : true,
			delay               : 5000,
			animationTime       : 200,
			easing              : "linear"
		});

	} else {
		jQuery('.t3_contentcontainerleft #slider2').parents('div.box').remove();
	}
	
	if (jQuery('#wppHighlights').length > 0) {
		jQuery('#wppHighlights').anythingSlider({
			width               : 295,
			height              : 32,
			resizeContents      : true, 
			buildArrows         : false,
			buildNavigation     : false,
			autoPlay            : true,
			showStartStop       : false,
			pauseOnHover        : true,
			delay               : 5000,
			animationTime       : 100,
			easing              : "swing"
		});
		
		
	}
	jQuery("#slide-jump").click(function(){
		$('#slider2').anythingSlider(4);
		return false;
	});
    
	jQuery('#tabs.dyn ul li a').removeAttr('onclick'); 
	jQuery('#tabs.dyn div:first').show(); // Show the first div
	jQuery('#tabs.dyn ul li:first').addClass('active'); // Set the class of the first link to active
	jQuery('#tabs.dyn ul li a').click(function(){ //When any link is clicked
		jQuery('#tabs.dyn ul li').removeClass('active'); // Remove active class from all links
		jQuery(this).parent().addClass('active'); //Set clicked link class to active
		var currentTab = jQuery(this).attr('href'); // Set variable currentTab to value of href attribute of clicked link
		jQuery('#tabs.dyn div.tabContent').hide(); // Hide all divs
		jQuery(currentTab).show(); // Show div with id equal to variable currentTab
		return false;
	});
	if ( jQuery.url.attr("anchor") == 'rentalSport2000' ) {
		jQuery('#tabs.dyn ul li a[href="#tabRentalSport2000"]').click();
	}
	if ( jQuery.url.attr("anchor") == 'rentalIntersport' ) {
		jQuery('#tabs.dyn ul li a[href="#tabRentalIntersport"]').click();
	}

	//**********************************
	//  Webcams   (immer am Schluss!)
    
	if (jQuery('.webcamPreview.loader div').length > 0) {
        
		var wcCnt = 1;
		var wcCnt2 = 1;
		jQuery('.webcamPreview.loader').bind('inview', function(event, isInView, visiblePartX, visiblePartY){
            
			if (isInView) {
            
				webcamUid = parseInt(jQuery('div', this).html());
				var targetEl = jQuery('div', this).parent();
            
				if (!jQuery(this).hasClass('loading')) {
					return '';
				}
				targetEl.removeClass('loading'); 
            
				// wir haben 4 Domains zur verfügung.
				if (wcCnt == 5) wcCnt = 1;
            
            
				var webcam = jQuery('div', this).html();
				var webcamArray = webcam.split(";");
				webcamUid = parseInt(webcamArray[0]);
				type = webcamArray[1];
				ajaxURLtmp = ajaxURL2.replace(ajaxUrlPlaceholder,'wc' + wcCnt);
				url = ajaxURLtmp + '&tx_mgskiresort_pi1[lang]=' + lang + '&tx_mgskiresort_pi1[action]=webcamSingle&tx_mgskiresort_pi1[webcam]=' + webcamUid + '&tx_mgskiresort_pi1[type]=' + type  ; 
            
            
				jQuery.ajax({
					"dataType": "jsonp",
					"url": url,
					"jsonpCallback": "webcamSingle" + wcCnt2, 
					"success": function(data) {
						targetEl.html(data['html']);
						targetEl.removeClass('loader');
					}
				});
            
           
				wcCnt++;
				wcCnt2++;
			}
		});
	}

	if (teaserOut) {
		teaserOut['url'] = document.URL; 
		jQuery.get('index.php?eID=mg_skiresort&action=teaserOut',teaserOut);
	}


});


function initMapX(id) {
	var map = new GMap2(document.getElementById(id + '_map'),{
		size: new GSize(400,400)
	});
	gdir = new GDirections(map, document.getElementById(id + '_dir'));
	from = jQuery('#'+id+'_from').val();
	to = jQuery('#'+id+'_to').val();
	setDirections(from, to, "de_DE");

	var IconEp = new GIcon(G_DEFAULT_ICON);
	IconEp.iconSize = new GSize(20,23) ; 
	IconEp.image = "http://"+jQuery.url.attr("host")+"/typo3conf/ext/mg_skiresort/res/img/gMap_marker_ep.png";
	IconEp.shadow = null;

	var marker = gdir.getMarker(0);

//map.removeOverlay(marker);
//var newMarker = new GMarker(marker.getLatLng(), IconEp);
//map.addOverlay(newMarker); 
}

function setDirections(fromAddress, toAddress, locale) {
	gdir.load("from: " + fromAddress + " to: " + toAddress,
	{
		"locale": locale
	});




}
function goToByScroll(id){
    
	if (jQuery("#"+id).length > 0 ) {
		jQuery('html,body').animate({
			scrollTop: jQuery("#"+id).offset().top
		},'slow');    
	}

}


function setResortlist(url,pid){
	jQuery.post('index.php?eID=mg_skiresort&action=setResortlist&url=' + encodeURIComponent(url) + '&pid=' + pid); 
}

function setExit() {
//jQuery.post('index.php?eID=mg_skiresort&action=setExit' ); 
}
function resetExit() {
//alert('resetExit');
//jQuery.post('index.php?eID=mg_skiresort&action=resetExit' );

}

function getListInfoAndUpdate() {
	jQuery.post('index.php?eID=mg_skiresort&action=getListInfo' ,'' , function(data){
		url = jQuery(data).find('ret').text() + '&type=997';
		getResortList(url);        
	},'xml');
}
function getExit() {

}

function getResortList(url) {
	showLoading();
	jQuery.ajax({
		type: "GET",
		url: url,
		cache: ajaxCache,
		dataType: "html",

		success: function(response,textStatus){
			var html=jQuery('#resortList',response).html(); 
			jQuery('#resortList').html(html);
			updateContentAferAjaxInList(response);
			hideLoading();
		}
	});

}


function activateRegion(region,srcOrg,MapCountry) {
	jQuery('.regiontext ul').find('a[id="'+region+'"]').addClass('aktiv') ;
	if (srcOrg) {
		//file = srcOrg.substring(mapFolder.length+2,srcOrg.length) ;
		file = jQuery.url.setUrl(srcOrg).attr('file');
		type = file.slice(0,1);
		filname= type+MapCountry+region+'.png';
		newSrc = baseURL +  mapFolder + '/'+ filname;

		jQuery('.mapcontainer .mapcontent img').attr('src', newSrc);    
	}


}

function deActivateRegion(region,srcOrg,MapCountry) {
	jQuery('.regiontext ul').find('a[id="'+region+'"]').removeClass('aktiv') ;
	if (srcOrg) {
		jQuery('.mapcontainer .mapcontent img').attr('src', srcOrg);
	}
}

function updateContentAferAjaxInList(response) {
	jQuery('.pagebrowser').html(jQuery('.pagebrowser',response).html());
	jQuery('.sortfields .right').html(jQuery('.sortfields .right',response).html());
	jQuery('#resortListFilterForm').html(jQuery('#resortListFilterForm',response).html());

	piVars = jQuery('#resortListFilterForm input[name="piVars"]',response).val();
	jQuery('#resortListFilterForm input[name="piVars"]').val(piVars);

	searchHeader = jQuery('.searchheader .text',response).html();
	jQuery('.searchheader .text').html(searchHeader);

	fieldsite = jQuery('.searchfields .fieldsite',response).html();

	jQuery('.searchfields .fieldsite').html(fieldsite);


}
//show loading bar

function showLoading(){
	if(jQuery("#loader").length == 0){
		jQuery('<div id="loader"><div id="loaderInner"><img src="/typo3conf/ext/mg_skiresort/res/img/ajax-loader_contactForm.gif" /></div></div>').appendTo('body');
		jQuery("#loader").show();
	//jQuery('#loaderInner').css('background-image','url(/typo3conf/ext/mg_skiresort/res/img/ajax-loader_contactForm.gif)');
	//jQuery('#loader').fadeTo(100,1);    

	}

}
//hide loading bar
function hideLoading() {
	jQuery('#resortList').show();
	jQuery("#loader").fadeTo(100, 0);
	/*jQuery('#resortList').fadeTo(250, 1);*/

	jQuery("#loader").remove();

};

function loadWebcams(uid) {
	return true;

	if (jQuery('#detailcontent .nav3_3').length > 0 ) {
		url = ajaxURL + '&tx_mgskiresort_pi1[action]=webcamsAll&tx_mgskiresort_pi1[uid]=' + uid;    
		showLoadingWebcams();
		jQuery.ajax({
			type: "GET",
			url: url,
			cache: ajaxCache,
			dataType: "html",
			success: function(response,textStatus){
				var html=jQuery('#content',response).html(); 
				jQuery('#detailcontent .nav3_3').html(html);
				hideLoadingWebcams();
			}
		});
	}
}


function showLoadingWebcams(){
	jQuery('#detailcontent .nav3_3').html('<div id="loader" ></div>');
	jQuery('#loader').fadeTo(100,1);
}
//hide loading bar
function hideLoadingWebcams(){
	jQuery("#loader").fadeTo(100, 0);
	jQuery("#loader").remove();

};

var headerregionFadeOut = 0;
function initRegionNavigation() {




	jQuery('#headerregionbutton').click(function(event){

		if (headerregionFadeOut == 1 ) return false;
		//jQuery('#headerregioncontent').toggle("slow");
		jQuery('#headercontainerlanguage').removeClass('back');
		jQuery('#headercontainerlink').removeClass('back');
		jQuery('#headercontainerlinkcontent').hide();
		jQuery('#headercontainerlanguagecontent').hide();

		if (jQuery('#headerregioncontent').css('display') == 'none') { 
			jQuery('#headerregionbutton .button').html('<img src="fileadmin/templates/inc/img/b_navi2_up.png" />');
		} else {
			jQuery('#headerregionbutton .button').html('<img src="fileadmin/templates/inc/img/b_navi2_down.png" />');
		}
		jQuery('#headerregioncontent').slideToggle("slow");
	//event.preventDefault();
	});

	// *********************************************************
	// Regionen Auswahl oben (Ausklappbox)
	jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][theatre]"]').live('click',function(){
		jQuery.regionTheatreClick(jQuery(this),false);    
	});

	jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][country]"]').live('click',function(){
		jQuery.regionCountryClick(jQuery(this),false);
	});

	jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][region]"]').live('click',function(){
		jQuery.regionRegionClick(jQuery(this),false);
	});

	jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][localregion]"]').live('click',function(){
		jQuery.localregionRegionClick(jQuery(this),false);
	});



	jQuery('#regionSelectForm a.submit').live('click',function(e){
		jQuery.submitRegionSelectForm();
		e.preventDefault();

	});

	jQuery('#headerregioncontent .regionshow').live('click', function(){
		jQuery(this).hide();
		jQuery('#headerregioncontent .regions').show();
		return false;
	});

	jQuery('#headerregionbutton').removeClass('inactive');
	jQuery('#headerregionbutton DIV.button img').removeClass('inactive'); 

}

var regionSubmit;
jQuery.extend({
	regionTheatreClick:  function(e,dbl) {
		regionSubmit = 0;
		jQuery('#theatreSelect div.buttons').html('');
		jQuery('#countrySelect div.buttons').html('');
		jQuery('#countrySelect select').html('');

		jQuery('#regionSelect div.buttons').html('');
		jQuery('#regionSelect select').html('');

		jQuery('#localregionSelect div.buttons').html('');
		jQuery('#localregionSelect select').html('');

		//ajaxURL = ajaxURL2.replace(ajaxUrlPlaceholder,'location');
		url = ajaxURL + '&tx_mgskiresort_pi1[action]=location&tx_mgskiresort_pi1[location][theatre]=' + e.val() + '&tx_mgskiresort_pi1[piVars]=' + jQuery('#regionSelectForm input[name="pivars"]').val();
        
		jQuery.ajax({
			type: "GET",
			url: url,
			cache: false,
			dataType: "html",
			success: function(response,textStatus){
				formAction = jQuery(response).find('#regionSelectForm').attr('action');
				if (dbl) {
					location.href= formAction;
				} else {
					html = jQuery(response).find('#countrySelect').html();
					regionSubmit = 1;
					jQuery('#countrySelect').html(html);

					button = jQuery(response).find('#theatreSelect div.buttons').html();
					jQuery('#theatreSelect div.buttons').html(button);



				}

			}
		});
	},
	regionCountryClick:  function(e,dbl) {
		regionSubmit = 0;
		jQuery('#countrySelect div.buttons').html('');

		jQuery('#regionSelect div.buttons').html('');
		jQuery('#regionSelect select').html('');

		jQuery('#localregionSelect div.buttons').html('');
		jQuery('#localregionSelect select').html('');

		var theatre = jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][theatre]"]').val();
		//ajaxURL = ajaxURL2.replace(ajaxUrlPlaceholder,'location');
		url = ajaxURL + '&tx_mgskiresort_pi1[action]=location&tx_mgskiresort_pi1[location][country]=' + e.val() + '&tx_mgskiresort_pi1[location][theatre]=' + theatre + '&tx_mgskiresort_pi1[piVars]=' + jQuery('#regionSelectForm input[name="pivars"]').val();
		jQuery.ajax({
			type: "GET",
			url: url,
			cache: false,
			dataType: "html",
			success: function(response,textStatus){
				formAction = jQuery(response).find('#regionSelectForm').attr('action');
                
				html = jQuery(response).find('#regionSelect').html();
				jQuery('#regionSelect').html(html);
				button = jQuery(response).find('#countrySelect div.buttons').html();
				jQuery('#countrySelect div.buttons').html(button);

				regionSubmit = 1;


				if (html == "") {
					jQuery('#headerregioncontent .regionshow').hide();
					jQuery('#headerregioncontent .regions').hide() ;                             
				} else {
					jQuery('#headerregioncontent .regionshow').show();
					jQuery('#headerregioncontent .regions').hide() ;
				} 

			}
		});    
	},
	regionRegionClick: function(e,dbl){
		regionSubmit = 0;
		jQuery('#regionSelect div.buttons').html(''); 


		jQuery('#localregionSelect div.buttons').html('');
		jQuery('#localregionSelect select').html('');

		var theatre = jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][theatre]"]').val();
		var country = jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][country]"]').val();
		//ajaxURL = ajaxURL2.replace(ajaxUrlPlaceholder,'location');
		url = ajaxURL + '&tx_mgskiresort_pi1[action]=location&tx_mgskiresort_pi1[location][region]=' + e.val() + '&tx_mgskiresort_pi1[location][theatre]=' + theatre + '&tx_mgskiresort_pi1[location][country]=' + country + '&tx_mgskiresort_pi1[piVars]=' + jQuery('#regionSelectForm input[name="pivars"]').val();
		jQuery.ajax({
			type: "GET",
			url: url,
			cache: false,
			dataType: "html",
			success: function(response,textStatus){
				formAction = jQuery(response).find('#regionSelectForm').attr('action');
				html = jQuery(response).find('#localregionSelect select').html();
				jQuery('#localregionSelect select').html(html);     
				button = jQuery(response).find('#regionSelect div.buttons').html();
				jQuery('#regionSelect div.buttons').html(button);
				regionSubmit = 1; 

			}
		});     
	},
	localregionRegionClick: function(e,dbl){
		regionSubmit = 0;

		jQuery('#localregionSelect div.buttons').html(''); 
		var theatre = jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][theatre]"]').val();
		var country = jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][country]"]').val();
		var region = jQuery('#headerregioncontent select[name="tx_mgskiresort_pi1[location][region]"]').val();

		//ajaxURL = ajaxURL2.replace(ajaxUrlPlaceholder,'location');
		url = ajaxURL + '&tx_mgskiresort_pi1[action]=location&tx_mgskiresort_pi1[location][localregion]=' + e.val() + '&tx_mgskiresort_pi1[location][theatre]=' + theatre + '&tx_mgskiresort_pi1[location][country]=' + country + '&tx_mgskiresort_pi1[location][region]=' + region + '&tx_mgskiresort_pi1[piVars]=' + jQuery('#regionSelectForm input[name="pivars"]').val() ;
		jQuery.ajax({
			type: "GET",
			url: url,
			cache: false,
			dataType: "html",
			success: function(response,textStatus){
				formAction = jQuery(response).find('#regionSelectForm').attr('action');
				button = jQuery(response).find('#localregionSelect div.buttons').html();
				jQuery('#localregionSelect div.buttons').html(button);

				regionSubmit = 1; 

			}
		});     
	},

	submitRegionSelectForm: function(){
		href =  jQuery('#regionSelectForm a.submit').attr('href');
		if (regionSubmit == 0) {
			setTimeout(function(){
				jQuery.submitRegionSelectForm();
			},20);
		} else {
			location.href= href;    
		}

	} 
});
function preDomLoad() {

	checkSuperBanner();
	// Elemente aktivieren!
	jQuery('.mapcontainer select[name=sort]').attr('disabled', false);
	jQuery('#resortListSearch input[name="sword"]').attr('disabled', false); 
	jQuery('.autoclear').autoclear();

	jQuery('input[name="tx_mgskiresort_pi1\\[resortlist\\]\\[specialfilter\\]\\[open\\]"]').attr('disabled', false); 


	jQuery('#cse-search-box input[name="q"]').removeAttr('disabled'); 
	// der Chrome behält sonst immer seine ausgegraute Farbe, blöder Workaround: 
	jQuery('#cse-search-box input[name="q"]').focus();
	jQuery('#cse-search-box input[name="q"]').blur();






	// Sortierung in Resortliste
	jQuery('.mapcontainer select[name=sort]').change(function(){
		showLoading();
		jQuery(this).attr('disabled', true); 
		window.location = jQuery(this).val();

	});

	// *********************************************************
	// Suche in Resortliste
	jQuery('#resortListSearch input[name="sword"]').keyup(function(e) {
		jQuery.updateSearchInput(jQuery(this));
		if(e.keyCode == 13) { 
			jQuery.searchResort();    
		}       

	});
	jQuery('#resortListSearch input[name="submit"]').click(function(){
		jQuery.searchResort();
		return false;
	});
	jQuery('#resortListSearch input[name="reset"]').click(function(){
		showLoading();
		window.location = jQuery('#resortListSearch input[name="searchresetaction"]').val();
	});




	// *********************************************************
	// Suche rechts oben
	var globalSearchDefaultVal = jQuery('#tx-indexedsearch-searchbox-sword').val();
	jQuery('#tx-indexedsearch-searchbox-sword').focus(function() {
		if (jQuery(this).val() == globalSearchDefaultVal) {
			jQuery(this).val('');    
		}  
	});
	jQuery('#tx-indexedsearch-searchbox-sword').blur(function() {
		if (jQuery(this).val() == '') {
			jQuery(this).val(globalSearchDefaultVal);    
		}  
	});
	if (jQuery('#detailcontent .nav3_3').length > 0 ) { 
		jQuery(".nav3_3 a.fancygroupImage").fancybox({
			'zoomSpeedIn': 300, 
			'zoomSpeedOut': 300, 
			'overlayShow': true,
			'type': 'image'
		});
		
		jQuery(".nav3_3 a.iframe").livequery(function(){
			jQuery(this).fancybox({
				height: 540,
				width: 570
			});
		});
	}

	if (jQuery('#detailcontent .nav5_1').length > 0 ) { 
		jQuery(".nav5_1 a.fancygroup").livequery(function(){
			jQuery(this).fancybox();
		});
	}


	if (jQuery('.box .webcamPreview').length > 0 ) { 
		jQuery(".box .webcamPreview a.fancygroup").livequery(function(){
			jQuery(this).fancybox();
		});
		jQuery(".box .webcamPreview a.iframe").livequery(function(){
			jQuery(this).fancybox({
				height: 540,
				width: 570
			});
		});

	}

	// *********************************************************
	// hover auf div funtkioniert beim IE leider nicht
	jQuery('#headerregionbutton').hover(function(){
		jQuery(this).children('.headerregionbuttontext').toggleClass('highlight');
		jQuery('#headerregionbutton .buttonWrapper').toggleClass('highlight');
	});

    
	// *********************************************************
	// HeaderNavi
	// DropDown Menu
	jQuery(".sf-menu").supersubs({ 
		minWidth:    14,   // minimum width of sub-menus in em units 
		maxWidth:    47,   // maximum width of sub-menus in em units 
		extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
	// due to slight rounding differences and font-family 
	}).superfish({ 
		disableHI:     true,
		delay:       12,                            // one second delay on mouseout 
		animation:   {
			opacity:'show',
			height:'show'
		},  // fade-in and slide-down animation 
		speed:       'fast',                          // faster animation speed 
		autoArrows:  false,                           // disable generation of arrow mark-up 
		dropShadows: false                            // disable drop shadows 
	});//.find('ul').bgIframe({opacity:false}); 



	// *********************************************************
	// Ein / auskplappen beim Testbericht
	//Box für die Testbericht Show Hide
	jQuery('.result .testberichte .colexp').click(function(event){
		var gotoID = jQuery(this).find('a').attr('class');
		if (gotoID) {
			goToByScroll(gotoID);    
			event.preventDefault();
		}
        
	});

	jQuery('.result .testberichte .rowshowhide .button a').click(function(event){
		goToByScroll('pRating');    
		event.preventDefault();
	});

	// *********************************************************
	// Zählen der extenen Links
	jQuery("a[href^='http:']").not("[href*='"+baseURL+"']").click(function(){
		jQuery.get('index.php?eID=mg_skiresort&action=externalLink','url=' + jQuery(this).attr('href')) ;
	});


	// *********************************************************
	// Sprungmarke beim Testbericht
	var anchor = jQuery.url.attr("anchor");
	if (anchor) {
		jQuery('a[id="' + anchor + '"]').parent().click();
		goToByScroll(anchor); 
	}

	// *********************************************************
	// Karte in Resorliste
	var srcOrg = jQuery('.mapcontainer .mapcontent img').attr('src');
	var MapCountry = jQuery('.mapcontainer #MapCountry').val();


	jQuery('.mapcontainer .regiontext a').mouseover(function(){
		region = jQuery(this).attr('id');

		if (region != '') {
			activateRegion(region,srcOrg,MapCountry);    
		}

	});
	jQuery('.mapcontainer map area').mouseover(function(){
		region = jQuery(this).attr('id');
		region = region.substring(1,region.length);
		activateRegion(region,srcOrg,MapCountry);    
	});

	jQuery('.mapcontainer .regiontext a').mouseleave(function(){
		region = jQuery(this).attr('id');
		if (region != '' ) {
			deActivateRegion(region,srcOrg,MapCountry);
		}
	});
	jQuery('.mapcontainer map area').mouseleave(function(){
		region = jQuery(this).attr('id');
		region = region.substring(1,region.length);
		deActivateRegion(region,srcOrg,MapCountry);

	});

	jQuery('.mapcontainer .moveup').mouseover(function(){
		var topVal = jQuery(this).parents(".map").find(".mapcontent").css("top");
		jQuery(this).parents(".map").find(".mapcontent").css("top", topVal-10);

	});



	// *********************************************************
	// Filter in Resortliste
	jQuery('input[name="tx_mgskiresort_pi1[resortlist][specialfilter][open]"]').click(function(){
		showLoading();
		window.location = jQuery('input[name="filterURL"]').val();
	});




	// Fancybox

	jQuery("a.fancygroup").fancybox({
		'zoomSpeedIn': 300, 
		'zoomSpeedOut': 300, 
		'overlayShow': true, 
		'imageScale': true
	});

	jQuery("a.fancygroup").removeAttr('onclick');  
	jQuery("a.fancygroupImage").removeAttr('onclick');  

	//**********************************
	//  Schneeberichtsteaser
     
	jQuery('.snowreportLoader.loader').bind('inview', function(event, isInView, visiblePartX, visiblePartY){
		var $el = jQuery('.hidden',this);
		resortUid = parseInt($el.html());
        
		if (isInView && $el && !isNaN(resortUid) ) {
                
			var targetEl = $el.parent();

			url = 'index.php?eID=mg_skiresort&action=snowreportTeaser&uid=' + resortUid + '&l=' + lang ; 
			jQuery.ajax({
				url: url,
				success: function(response,textStatus){
					targetEl.html(jQuery('html', response).text());
					targetEl.removeClass('loader');        
				}
			});

		}
        
        
        
        
	});
    
/*
    if (jQuery('.snowreportLoader .hidden').length > 0) {
        
        jQuery('.snowreportLoader .hidden').each(function() {
            
            
            resortUid = parseInt(jQuery(this).html());    
            var targetEl = jQuery(this).parent();

            url = 'index.php?eID=mg_skiresort&action=snowreportTeaser&uid=' + resortUid + '&l=' + lang ; 
            jQuery.ajax({
                url: url,
                success: function(response,textStatus){
                    targetEl.html(jQuery('html', response).text());
                    targetEl.removeClass('loader');        
                }
            });

        });


    }
      */

}


// Tiscover
jQuery(document).ready(function() {
	jQuery("#jse").val("1");
	jQuery("#c, #c0, #c1, #c2, #c3").change(cChanged);
	if (lang == 'de') {
		jQuery("#sd").val(jQuery.datepicker.formatDate('dd.mm.yy', new Date(new Date().getTime() + (1000*60*60*24))));
		jQuery("#ed").val(jQuery.datepicker.formatDate('dd.mm.yy', new Date(new Date().getTime() + (1000*60*60*24*8))));
	} else {
		jQuery("#sd").val(jQuery.datepicker.formatDate('dd.mm.yy', new Date(new Date().getTime() + (1000*60*60*24))));
		jQuery("#ed").val(jQuery.datepicker.formatDate('dd.mm.yy', new Date(new Date().getTime() + (1000*60*60*24*8))));
	}
	jQuery("#sd").datepicker({
		dependOn: "#ed", 
		triggerHandle: "#sd-handle"
	});
	jQuery("#ed").datepicker({
		minDate: '1d', 
		dependOn: "#sd", 
		triggerHandle: "#ed-handle", 
		beforeShowDay : jQuery.datepicker.disableDatesBeforeDependentDatepickerValue, 
		monthPosBasedOnDependent: true
	}); 

	jQuery(function(){
		jQuery.datepicker.regional['de'] = {
			clearText: 'löschen', 
			clearStatus: 'aktuelles Datum löschen',
			closeText: 'schließen', 
			closeStatus: 'ohne Änderungen schließen',
			prevText: '&#x3c;zurück', 
			prevStatus: 'letzten Monat zeigen',
			nextText: 'Vor&#x3e;', 
			nextStatus: 'nächsten Monat zeigen',
			currentText: 'heute', 
			currentStatus: '',
			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'],
			monthStatus: 'anderen Monat anzeigen', 
			yearStatus: 'anderes Jahr anzeigen',
			weekHeader: 'Wo', 
			weekStatus: 'Woche des Monats',
			dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
			dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			dayStatus: 'Setze DD als ersten Wochentag', 
			dateStatus: 'Wähle D, M d',
			dateFormat: 'dd.mm.yy', 
			firstDay: 1, 
			initStatus: 'Wähle ein Datum', 
			isRTL: false
		};

		jQuery.datepicker.regional['en'] = {
			dateFormat: 'dd.mm.yy'
		};
		if (lang=='de') {
			jQuery.datepicker.setDefaults(jQuery.datepicker.regional['de']);
		} else {
			jQuery.datepicker.setDefaults(jQuery.datepicker.regional['en']);
		}
	});

	jQuery.datepicker.setDefaults({
		numberOfMonths : 2,
		showOtherMonths : true,
		showOn : 'both',
		firstDay : 1, 
		minDate : '0d',
		maxDuration : 50,
		onClose : function(date) {
			var startDate = jQuery.datepicker.parseDate('dd.mm.yy', jQuery("#sd").val());
			var endDate = jQuery.datepicker.parseDate('dd.mm.yy', jQuery("#ed").val()); 
			if (startDate.getTime() >= endDate.getTime()) {
				jQuery("#ed").val(jQuery.datepicker.formatDate('dd.mm.yy', new Date(startDate.getTime() + (1000*60*60*24))));
			}
		//jQuery.datepicker.validate("#sd", "#ed", "#datepickerErrorField"); 
		},
		beforeShowDay : jQuery.datepicker.highlightDependentDatepickerValue
	});

	if (lang != 'de') {
		jQuery.datepicker.setDefaults({
			onClose : function(date) {
				var startDate = jQuery.datepicker.parseDate('dd.mm.yy', jQuery("#sd").val());
				var endDate = jQuery.datepicker.parseDate('dd.mm.yy', jQuery("#ed").val()); 
				if (startDate.getTime() >= endDate.getTime()) {
					jQuery("#ed").val(jQuery.datepicker.formatDate('dd.mm.yy', new Date(startDate.getTime() + (1000*60*60*24))));
				}
			//jQuery.datepicker.validate("#sd", "#ed", "#datepickerErrorField"); 
			}
		}); 
	}


});

function cChanged() {
	(this.id.length == 1) ? id = "" : id = this.id.substr(1);
	value = jQuery(this).val();
	jQuery("#room"+id+" #ca").addClass("h");
	jQuery("#room" + id + " .cage").addClass("h");
	jQuery("#room" + id + " .cage input").attr("disabled", "disabled");

	if (value > 0) {
		for (i = 0; i < value; i++) {
			jQuery("#room" + id + " .rca" + i + ", #room" + id + " #ca").removeClass("h");
			jQuery("#room" + id + " .rca" + i + " select").attr("disabled", null);
		}
	}
}

/** missing functionality 
* copy values from #room to #room1 when nr of rooms changed
* after changing of room lines examine values of chage to correctly display chage select boxes
*/





if (jQuery.browser.msie) {
	if (parseInt(jQuery.browser.version, 10) < 7) {
		jQuery.datepicker.setDefaults({
			duration: '',
			numberOfMonths: 1,
			beforeShowDay : jQuery.datepicker.highlightDependentDatepickerValue
		});
	} else if (parseInt(jQuery.browser.version, 10) < 8) {
		jQuery.datepicker.setDefaults({
			duration: '',
			numberOfMonths: 2,
			beforeShowDay : jQuery.datepicker.highlightDependentDatepickerValue
		});
	}
}

Date.prototype.toJulianDate = function() {
	MM = this.getMonth() + 1;
	DD = this.getDate();
	YY = this.getFullYear();
	with (Math) {  
		GGG = 1;
		if (YY <= 1585) GGG = 0;
		JD = -1 * floor(7 * (floor((MM + 9) / 12) + YY) / 4);
		S = 1;
		if ((MM - 9)<0) S=-1;
		A = abs(MM - 9);
		J1 = floor(YY + S * floor(A / 7));
		J1 = -1 * floor((floor(J1 / 100) + 1) * 3 / 4);
		JD = JD + floor(275 * MM / 9) + DD + (GGG * J1);
		JD = JD + 1721027 + 2 * GGG + 367 * YY;
		}
	return JD;
};
var checkSuperBannerCnt = 0;
function checkSuperBanner() {
    
	checkSuperBannerCnt++;
	
	if (DOMReady) {
	/*
		if (jQuery('#adWrapper #ad object').length > 1) {
            // Ist wohl ein Wallpaper
            jQuery('#adWrapper').addClass('hasNoAd');
		} else if ((jQuery('#adWrapper #ad div').html() != null ) || jQuery('#adWrapper #ad object').length > 0 || jQuery('#adWrapper #ad img').height() > 1) {
            jQuery('#adWrapper').addClass('hasAd');
            jQuery('#adWrapper').removeClass('hasNoAd');  
        } else {
            jQuery('#adWrapper').removeClass('hasAd');
            jQuery('#adWrapper').addClass('hasNoAd');
        }
		*/
	} 
    
	// Andere banner testen
	jQuery('.promotionAdContainer .col1 .promotionAd').each(function (){
		if (!jQuery(this).parents('.promotionAdContainer').hasClass('active')) {
			jQuery(this).parents('.promotionAdContainer').addClass('active');
		}
	});
	// google Ads
	jQuery('.promotionAdContainer').each(function() {
		if (jQuery(this).find('ins').length > 0) {
			jQuery(this).addClass('active');  
		}
	});

	showLinkTipp = 0;
	jQuery('.box .boxcontent .tx-mgskiresort-pi4').each(function(){
		if (jQuery(this).contents('div').size() > 0) {
			showLinkTipp = 1;
		}
		el =  jQuery(this);
		if (showLinkTipp == 0) {
			el.parents('.box').hide();
		} else {
			el.parents('.box').show();
		}
	});
    
    
	if (checkSuperBannerCnt <= 4 && DOMReady) {
		window.setTimeout("checkSuperBanner()", 1000);
	}

}


function formatSliderText(index, panel){
	return jQuery(panel).find('input[name="headline"]').val();;
}
function linkSliderText(index, panel) {
	return jQuery(panel).find('.header h2 a').attr('href');
}
function linkSliderText2(index, panel) {
	return jQuery(panel).find('.row2 a').attr('href');
}

function openTrailmapWindow(url) {
	var sw = screen.width-10;
	var sh = screen.height-100;

	window.open(url,'trailmap','width='+sw+',height='+sh+',left=0,top=0,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no');

}

var focus_timer; 
function windowOpen(url) {
	jQuery.get("index.php?eID=mg_skiresort&action=externalLink","url=" + url) ;
	newWin = window.open(url);
	focus_timer= setInterval("try{newWin.focus()}catch(err){}", 500); 
    
}

