//JQUERY
$.extend($.expr[':'], {
	// case insensitive version of :contains
	icontains: function(a,i,m){return (a.textContent||a.innerText||jQuery(a).text()||"").toLowerCase().indexOf(m[3].toLowerCase())>=0;}
});

//jQuery.noConflict();

$(document).ready(function(){
	
	//if iPhone or if iPad
	function isiOS() {
	    return (
	        (navigator.platform.indexOf("iPhone") != -1) ||
	        (navigator.platform.indexOf("iPad") != -1)
	    );
	}
		
	//Current window.location
	var uri = window.location.href;
	var pathname = window.location.pathname;
	var hash = window.location.hash;
	var nohash = uri.replace(location.hash,"")
	
	
	//Label inside of inputfields
	function insidelabel(selector, name) {
		$(selector).val(name);
		$(selector).css({'color':'#999'});
		
		$(selector).focus(function () {
			//Input Value
			if ($(this).val() == name) { $(this).val(''); }
			$(this).css({'color':'#465356'})
		});
		
		$(selector).blur(function () {
			if ($(this).val() == '') { $(this).val(name); }
			if ($(this).val() == name) {
				$(this).css({'color':'#999'});
			}
		});
	}
	
	//Forum
	//insidelabel('.wpf-textarea', 'Dein Beitrag');
	
	//Label inside of inputfields
	(function () {
		var fill = "fill";
		var inputs = jQuery('.input-inside-label input, .search-input-inside-label input, .textarea-inside-label textarea');
		var setLabelStyle = function setLabelStyle () {
			var label = $(this);
			if (label.val().length) {
				label.addClass(fill);
			} else {
				label.removeClass(fill);
			}
		};
		inputs.focus(function () { $(this).addClass(fill); });
		inputs.blur(setLabelStyle);
		inputs.each(setLabelStyle);
	}());
	
	//Ajax-based search
	var $sr = $('#searchresults');
	var $srl = $('#search_form .s_loader');
	var $src = $('#search_form .s_closer');
	var $srh = $('#searchresults-header');
	
	function clearsearch(clear) {
		if (clear) $('.s').val('');
		$sr.children().remove();
		$sr.slideUp('fast');
		$srl.fadeOut('fast');	
		$src.fadeOut('fast');
		$srh.slideUp('fast');
		$('.s').removeClass('s_loader');
		$('.s').focus();
	}
	
    var searchTimer, jqXHR_Old;
    var maxResults = 10;
	
	function doSearch(keyCode) {
		
		var input = $('.s').val();

		//key navigation through elements
		if (keyCode == 38 || keyCode == 40 || keyCode == 13) {
						
			var $results = $('#searchresults ul li.matched');
			 
			var $current = $results.filter('.selected'),
		        $next,
				$go,
				$anchor,
				$path;

			switch ( keyCode ) {
		    	case 38: // Up
			        $next = $current.prev();
			        break;
			    case 40: // Down
					if (!$results.hasClass('selected')) {
				   		$results.first().addClass('selected');
					}
			        $next = $current.next();				
			        break; 
			    case 13: // Enter
					if ($results.hasClass('selected')) {
						
						$go = $current.find('a').attr('href');
						$path = $go.split('#')[0];						
						$anchor = $go.split('#')[1];

						//scroll to anchor link
						if ( $anchor != undefined && uri.indexOf($path) != -1 ) {
							
							//google map							
							if ( $anchor == 'mapContainer' ) {
								$('#googleMap').click();
							}
							
							if ( $("a[name='#"+$anchor+"']").length > 0 ) {
								scroll( $("a[name='#"+$anchor+"']"), true, true, 30);
							} else if ( $("#"+$anchor).length > 0 ) {
								scroll($("#"+$anchor), true, true, 30);
							} else {
								location.href = $go;
							}

						} else {
							location.href = $go;
						}
			
					} else {
						location.href = "/?s=" + $('.s').val();
					}
					break;
		    }
			
			if ( keyCode != 13 ) {
				
				//only check next element if up and down key pressed
		    	if ( $next.is('li') ) {
			        $current.removeClass('selected');
			        $next.addClass('selected');
			    }
		
				//update text in searchbar
				if ($results.hasClass('selected')) {
					$('.s').val($('.selected').text());
				}
				
			}
			
			return;
		}
		
		if (input !== '') {
			
			searchTimer = 0;
			
			$src.fadeOut('fast');
			$srl.fadeIn('fast');
			
			if (jqXHR_Old) {
                // abort the previous request
                jqXHR_Old.abort();
                jqXHR_Old = null;
            }

			var data = {
				action: 'searchmap'
			};

			jqXHR_Old = $.post( Searchmap.ajaxurl, data, function(response) {
				
				$sr.html(response);
				$('#searchresults ul li').removeClass('selected');
				
				$srl.fadeOut('fast');				

				var found = $('#searchresults ul li:icontains("' + input + '")');
				found.addClass('matched');
			
				//show results only if there are any
				if ($('#searchresults ul li').hasClass('matched')) {
					$srh.slideDown('fast');
					$src.fadeIn('fast');
					$sr.slideDown('fast');
				} else {
					//clear search
					clearsearch(false);
					$('#searchresults ul li.matched').each(function() {
						$(this).removeClass('selected');
					});
				}
			
				//remove all remaining list-items
				$('#searchresults ul li').not('.matched').remove();
				//max number of results
				$('#searchresults ul').children().slice(maxResults).remove();
				
				//highlight results -> causes browser crash
				$('#searchresults ul li.matched').highlight(input);
			
				//apply class if item is exactly matched				
				$('#searchresults ul li.matched').each(function() {
					if ($(this).text().toLowerCase() === input.toLowerCase()) {
						$(this).addClass('selected');
						$('.s').val($('.selected').text());
					}
				})
			
				/*remove selected color on hover*/
				$('#searchresults ul > li').mouseenter(function () {
					$(this).addClass('selected').siblings().removeClass('selected');
				});
				
				jqXHR_Old = null;
				
		    });

		} else {
			clearsearch(true);
		}
	}
	
	$('.s').keyup(function(e) {

		switch (e.keyCode) {
			//case 8:  // Backspace
			case 9:  // Tab
			case 13: // Enter
				doSearch(e.keyCode);
				break;
			case 16: // Shift
			case 17: // Ctrl
			case 18: // Alt
			case 19: // Pause/Break
			case 20: // Caps Lock
			case 27: // Escape
			case 35: // End
			case 36: // Home
			case 37: // Left
				break;
			case 38: // Up
				doSearch(e.keyCode);
				break;
			case 39: // Right
				break;
			case 40: // Down
				doSearch(e.keyCode);
				break;
			// Mac CMD Key
			case 91: // Safari, Chrome
			case 93: // Safari, Chrome
			case 224: // Firefox
			break;

			default:
			if (searchTimer !== null) {
				clearTimeout(searchTimer);
			}
			
			searchTimer = setTimeout(function () {
			    doSearch(e.keyCode);
			}, 250);
		}

	});
	
	//maintain cursor position when pressing up key
	$('.s').bind('keydown keypress',function(e) {
	    if (e.keyCode == 38 || e.keyCode == 40) {
	        e.preventDefault();
	    }
	});
	
	$('#search_form').submit(function(e) {
		e.preventDefault();
	});
	
	$('#search_form .s_closer').click(function() {
		clearsearch(true);
	});
	
	//Animated scroll for anchorlinks
	var highlightCol = '#EEEEDC',
		delayTime = 500,
		fadeInTime = 300,
		fadeOutTime = 300,
		highlightTime = 1000;
		
	$("a[href*='#']").live('click', function(e) {

		//$(this).addClass('anchorLink');
		
		var path = $(this).attr('href').split('#')[0];
		var anchor = $(this).attr('href').split('#')[1];
		
		//if ( uri.indexOf(path) != -1 ) {
			
		//if ( nohash == path ) {

		if ( nohash == path || nohash == path+"/" || nohash == nohash+path ) {
		
			if ( $("a[name='#"+anchor+"']").length > 0 ) {
				e.preventDefault();
				scroll($("a[name='#"+anchor+"']"), true, true, 30);
			} else if ( $("#"+anchor).length > 0 ) {
				e.preventDefault();
				scroll($("#"+anchor), true, true, 30);
			}
		
		}
		
	});
	
	function scroll(selector, animate, highlight, viewOffset) {
		
		var bgCol = $(selector).css('backgroundColor');
		
		var pageOffset = $(selector).offset();
		var scrollPos = pageOffset.top - viewOffset;
		
		if (animate) {
		
			$('html, body').animate({scrollTop : scrollPos + 'px'}, {
		        duration: 'slow',
		        easing: 'easeOutQuint',
		        complete: function() { }
			});
		
		} else {
		
			$('html, body').scrollTop( scrollPos );
			
		}
		
		//highlight element
		if ( highlight && ( bgCol != "rgba(0, 0, 0, 0)" && bgCol != "transparent" ) ) {
			$(selector).delay(delayTime).animate({ backgroundColor: highlightCol }, fadeInTime).delay(highlightTime).animate({ backgroundColor: bgCol }, fadeOutTime);
		}
		
	}
	
	//Breadcrumbs and content maintain scrollposition
	$('#b a, #main a:not([href*="#"]):not([href*="mailto:"])').live('click',function() { // .not('[href*="?mingleforumaction="]')
	    $(this).attr('href', $(this).attr('href') + "#b");     
	});
	
	//Target _blank for RSS Widget links
	$('a.rsswidget').each(function() {
		$(this).attr('target','_blank');
	});
	
	function mediaQuery() {
		//Fix nth-child bug in IE
		if ($.browser.msie) {
	
			if ( $('.inner').width() <= 648 ) {
				$('#footerwidgets .widget-area ul.xoxo > li:nth-child(2n), footer .widget-area ul.xoxo > li:nth-child(2n), #forum-header .widget-area ul.xoxo > li:nth-child(2n)').addClass('second');
				$('#footerwidgets .widget-area ul.xoxo > li:nth-child(3n)').removeClass('third');
			} else {
				$('#footerwidgets .widget-area ul.xoxo > li:nth-child(2n), footer .widget-area ul.xoxo > li:nth-child(2n), #forum-header .widget-area ul.xoxo > li:nth-child(2n)').removeClass('second');
				$('#footerwidgets .widget-area ul.xoxo > li:nth-child(3n)').addClass('third');
			}
			
		}
	}
	
	mediaQuery();
	
	$(window).resize(function() {
		mediaQuery();
	});
	
	//Add Forum breadcrumbs
	if ( $("#wpf-wrapper").length > 0 ) {
		var forumCrumbs = $('#trail').html().replace( new RegExp("<strong>»</strong>", 'g'), "<span class='separator'>&rang;</span>" );
		$('#b .inner').append(forumCrumbs);
		var lc = $('#b .inner a:last-child').text();
		$('#b .inner a:last-child').remove();
		$('#b .inner').append(lc);	
	}
	
	//Forum no cellspacing and cellpadding
	$('#wpf-wrapper .wpf table').each(function() {
		$(this).attr('cellspacing', 0);
		$(this).attr('cellpadding', 0)
	});
	
	//Forum Search Inputs
	$('#wpf-wrapper .wpf-table .wpf-input').addClass('input-field');
	$('#wpf-wrapper #wpf-search-submit').parent('td').removeAttr('align');
	$('#wpf-wrapper #wpf-search-submit').addClass('btn orange small width320');
	
	//Forum remove bbcodes
	$('#wpf-wrapper #wpf-quick-reply a, #wpf-wrapper #wpf-quick-reply br:first, #wpf-wrapper form[name"addform"] .wpf-table a, #wpf-wrapper form[name"addform"] .wpf-table br').remove();
	$('#wpf-wrapper #wpf-quick-reply td strong:contains("Direktantwort")').text('Antworten');
	
	//Forum style inputs
	$('#quick-reply-submit, #wpf-post-submit').addClass('btn small orange rarr width480');
	
	//Forum
	$('#wpf-wrapper a[title="Profil anzeigen"]').contents().unwrap().wrap('<span class="forum-user" />');;
	
	//remove <br>'s from gallery
	$('.gallery br').not(':last-child').each(function() {
		$(this).remove();
	});
	$('.gallery dl.gallery-item').animate({ opacity : 1 }, 'slow');
	
	//Add title attribute to download links
	$("a[href$='.pdf'], a[href$='.xls'], a[href$='.xlsx'], a[href$='.doc'], a[href$='.docx'], a[href$='.ppt'], a[href$='.pptx'], a[href$='.pps'], a[href$='.zip'], a[href$='.gzip'], a[href$='.rar'], a[href$='.txt'], a[href$='.rtf']").attr('title', 'Diese Datei downloaden?');
	
	//select box	
	var currentSelectDiv = null;
	$('.select ul li.option').click(function(e) {
	    //storing the id attribute
	    currentSelectDiv = $(this).parents("div.select").attr("id");

	    $(this).siblings().slideToggle(100).removeClass('darr');
	    $(this).addClass('darr');
	});

	$(document).click(function(e) {
	    $('.select ul li.option').each(function() {
	        // check IDs to make sure only closing other lis
	        if( $(this).parents("div.select").attr("id") !=
	           currentSelectDiv) {
	            if ( !$(this).is(":hidden" ) ) {
	                $(this).not('.darr').slideToggle(100);
	            }
	        }
	    });
	    currentSelectDiv = null;
	});
	
	
	// #öbb
	$('#oebb .select ul li.loc').click(function() {
		$('.prefixedLocation').attr('value', $(this).attr('title'));
	});
	$('#oebb .select ul li.dest').click(function() {
		$('.prefixedDestiny').attr('value', $(this).attr('title'));
	});
	
	// #contactform
	$('#contactform .select ul li.option').click(function() {
		$('.type').attr('value', $(this).attr('rel'));
	});
	// #weather
	$('li#weather').addClass($('#condition').attr('class'));
	$('#condition').removeAttr('class');
	
	//Submit forms
	$('#bus-search, #chemist-search').click(function(e) {
		e.preventDefault();
		$(this).parent('form').submit();
	});
	
	$('#chemist').submit(function(e) {
	    var $input = $(this).find('.grab-label');

	    if ( !$input.val().length ) {
	        $input.val($input.prev().text());
			$input.focus();
	    }
	});
	
	$('#ctl00_ContentPlaceHolder1_SubmitButton').hover(
		function() {
			$('#weekend-search').toggleClass('btn-orange-hover');
		}
	);
	
	//Back to top
	$(window).scroll(function () {
		
		if ( $(window).width() > 300 || !isiOS ) {
		
			if ( $(window).scrollTop() > 100 ) {
				$('#back-to-top').fadeIn('fast');
			} else {
				$('#back-to-top').fadeOut('fast');
			}
			
		}
		
    });
	
	$(window).scroll();
	
	//Google Maps API
	$('#googleMap').live('click', function(e) {
		
		e.preventDefault();
	
		if ( !$('#mapBottomContainer').children().size() > 0 ) {
		
			scroll( $('#mapBottomContainer'), true, false, 30 );
		
			$('#mapBottomContainer').animate({
			    'height': '450px'
			     },{
			    duration: 'fast',
			    complete: function () {
				
			       	loadMap("mapBottomContainer", false);
					$('#mapBottom .googleMapCloser, #mapBottom .googleMapFull').fadeIn('fast');
				
			    },
			    queue: false
			});			
		}
	
	});
	
	$('#mapBottom .googleMapCloser').live('click', function() {
		$(this).fadeOut(300);
		$('#mapBottom .googleMapFull').fadeOut(300);
		$('#mapBottomContainer').animate({'height':'0px' }, 'slow', function() {
			$(this).children().remove();
		});
	});
	
	$('#mapBottom .googleMapFull').live('click', function() {
		
		if ( isiOS ) {
		    top.location.hash = "map";
		} else {
			window.location = "http://goo.gl/h5eEy";
		}
		
	});
	
	$('#mapFullscreen .mapFullScreenTopBar').live('click', function() {
		$('#mapFullscreen').fadeOut(300, function() { $('#mapFullscreenContainer').children().remove(); });
		top.location.hash = "_";
	});
	
	$(window).bind( 'hashchange', function( event ) {
	
        if (window.location.hash == "#map"){
           
			$('#mapFullscreen').fadeIn('fast', function () {
				loadMap("mapFullscreenContainer", true);
	        })

        } else {
            $('#mapFullscreen').fadeOut(300, function() { $('#mapFullscreenContainer').children().remove(); });
        }

	});
	
	$(window).trigger("hashchange");
	
	function loadMap(cont, scroll) {
		
		var latlng = new google.maps.LatLng(47.244236,11.249194);
		var c = new google.maps.LatLng(47.24975839423972,11.24856583068845); //optical center
		var options = {
			zoom: 14,
			center: c,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			scrollwheel: scroll,
			streetViewControl: false,
			navigationControlOptions: {  
			    style: google.maps.NavigationControlStyle.SMALL 
			}
		}

		var map = new google.maps.Map(document.getElementById(cont), options);

		//only show link if not fullscreen
		/*var link = '';
		if (window.location.hash != "#map") {
			link = '<a href="#map" title="Vollbild Modus">Vollbild Modus</a></p>';
		}*/

		var mapdesc = '<div id="gmContent">'+
		'<h3 id="gmTitle" class="widget-title">oberpervens (Atlas Tyrolensis)</h3>'+
		'<div id="gmBody">'+
		'<p>Die berühmte Tirol-Karte von <b>1774</b> mit dem Namen ' +
		'„Atlas Tyrolensis“ ist das Werk zweier hochbegabter Autodidakten aus Oberperfuss: ' +
		'<a href="/die-gemeinde/beruehmte-persoenlichkeiten/#b" title="Berühmte Persönlichkeiten">Peter Anich und Blasius Hueber</a><br/>'+
		//'<a href="#map" title="Vollbild Modus">Vollbild Modus</a></p>'+
		//link+
		'</div>'+
		'</div>';

		var infowindow = new google.maps.InfoWindow({
			content: mapdesc
		});

		var marker = new google.maps.Marker({
			position: latlng,
			map: map,
			title: '6173 Oberperfuss'
		});

		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map,marker);
		});

		infowindow.open(map,marker);
		
	}	
	
	//Comment form
	$("#comment").focus(function() {
		$(this).css({"background-color":"#fff"});
		$(this).animate({backgroundPosition: '220% 16px'}, {
			duration: 500,
	        easing: 'easeOutQuint',
	        complete: function() { }
		});
    });

	$("#comment").blur(function() {
		if ( $(this).val() == '' ) {
			$(this).css({"background-color":"transparent"});
			$(this).animate({backgroundPosition: '100% 16px'}, {
				duration: 500,
		        easing: 'easeOutQuint',
		        complete: function() { }
			});
		}
    });

	//Q&A FAQ's
	$('.qanda .question').click(function() {
		$(this).parent().children('.answer').slideToggle('fast');
		$(this).toggleClass('active-question');
	});
	
	
	if ($.browser.msie && $.browser.version.substr(0,1)<9) { // if ie6 || ie7 || ie8
		
		var browserTip = $.cookie('browser_tip');
				
		if (browserTip != 'on') {
		    $('#newbrowser').show();
		}
		
		//Browser Tip
		$('#newbrowser .getnewbrowserCloser').click(function() {
			$(this).parent().slideUp({
				duration: 300,
		        easing: 'easeOutQuint',
		        complete: function() { 
					$('#newbrowser').remove();
					$.cookie('browser_tip', 'on', { expires: 1000 });
				}
			});
		});
		
	}
	
	//Same height for all footer widgets
	function widgetsSameHeight( elements ) {
							
		if ( $(window).width() > 768 ) { // 1column
			
			var max_height = 0;
			elements.each(function(){
			     if( $(this).height() > max_height ){
			        max_height = $(this).height();   
			    }
			});

			elements.height(max_height);
		} else {
			elements.removeAttr('style');
		}
	}

	function sameHeight() {
		widgetsSameHeight( $('#forum-header .widget-container') );
		widgetsSameHeight( $('#footerwidgets .widget-container') );
		widgetsSameHeight( $('footer .widget-container') );
	};

	//Hack for Wochenenddienste der Ärztekammer
	function weekendHack() {
		$('#weekend-search, #ctl00_ContentPlaceHolder1_SubmitButton').width( $('#bus-search').width() );
	};
	
	//auto resize Youtube Videos
	function resizeYoutubeVids() {
		
		var vid = $('.entry object, .entry object embed');
		var vidWidth = vid.attr('width');
		var vidHeight = vid.attr('height');
		
		if ( $('.inner').width() == 1068) {
			
			var pro =  Math.round((vidHeight/vidWidth)*690);
			vid.attr('width', '690');
			vid.attr('height', pro );
			
			
		} else if ( $('.inner').width() == 648) {
			
			var pro =  Math.round((vidHeight/vidWidth)*390);
			vid.attr('width', '390');
			vid.attr('height', pro );
			
		} else if ( $('.inner').width() == 300 ) {
			
			var pro =  Math.round((vidHeight/vidWidth)*290);
			vid.attr('width', '290');
			vid.attr('height', pro );
			
		}
		
	}
	
	weekendHack();
	sameHeight();
	resizeYoutubeVids();

	$(window).resize(function() {

		weekendHack();
		sameHeight();
		resizeYoutubeVids();

	});
	
	//Contact send
	if( window.location.hash == "#success" ) {
	  	$('#contactform').hide();
		$('#message').append("<div class='contactfeedback success'>Danke - Ihre Nachricht wurde erfolgreich übermittelt.</div>");
		window.location.hash == "#b";
	} else if ( window.location.hash == "#error" ) {
	  	$('#contactform').hide();
		$('#message').append("<div class='contactfeedback error'>Fehler - Ihre Nachricht konnte leider nicht erfolgreich übermittelt werden. <a href='http://www.oberperfuss.at/kontakt'>Erneut versuchen?</a></div>");
		window.location.hash == "#b";
	}
	
	//Print Document
	$('#print').click(function(e) {
		e.preventDefault();
		window.print();
	});
	
	//Dorfblatt
	$('a[href*="oberperfer-dorfblatt"]').click(function(e) {
		e.preventDefault();
		window.open("http://www.oberperfuss.at", "dorfblatt");
	});
	
	//Fundamat Online
	$('a[href*="fundamt-online"]').click(function(e) {
		e.preventDefault();
		window.open("http://www.fundinfo.at/suche/MyApp.asp?wci=Suche1&Mdt=41999", "fundamt");
	});
	
	//My_Calendar Plugin Localization
	$('#nextMonth').text('Nächstes Monat »');
	$('#prevMonth').text('« Vorheriges Monat');
	$('.event-time').append(' Uhr')
	
	//My_Calendar Plugin Sub-Details on hover
	$("#jd-calendar .calendar-event").hover(
		function () {

			var el = $(this).children('.details').children('.sub-details');

			if( el.children('.longdesc').text().length > 10 ) {

				el.fadeIn('fast');
			}
			
		},
		function () {
			$(this).children('.details').children('.sub-details').fadeOut('fast');
		}
	);
	
	//My_Calendar Plugin - remove time if not set
	$('.details span.event-time').each(function() {
		var text = $(this).text();
		text = $(this).text().replace('n/v', '');
		$(this).text(text);
		text = $(this).text().replace('Uhr', '');
		$(this).text(text);
	});
	
	//Add class if target blank
	$("#main .entry a[target='_blank']:not([href*='mailto:'])").addClass('web');
	
	//Style google +1 button
	$('#___plusone_0').css('padding-left', '8px');
	
});
