/* Author: Timo de Winter

*/

$(document).ready(function() {
	
	if(('#main_nav').length>0){
		ddsmoothmenu.init({
			mainmenuid: "main_nav", //menu DIV id
			orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
			classname: 'menu', //class added to menu's outer DIV
			//customtheme: ["#1c5a80", "#18374a"],
			contentsource: "markup", //"markup" or ["container_id", "path_to_menu_file"]
			arrowimages: {
				down:['downarrowclass', TEMPLATE_URL+'/img/down.png', 23],
				right:['rightarrowclass', TEMPLATE_URL+'/img/right.png']},
			transition: {overtime:300, outtime:600}, //duration of slide in/ out animation, in milliseconds
			shadow: {enable:false, offsetx:5, offsety:5}, //enable shadow?
			showhidedelay: {showdelay: 100, hidedelay: 200} //set delay in milliseconds before sub menus appear and disappear, respectively
		});
	}

	if(('#sub_nav').length>0){
		ddsmoothmenu.init({
			mainmenuid: "sub_nav", //menu DIV id
			orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
			classname: 'menu', //class added to menu's outer DIV
			//customtheme: ["#1c5a80", "#18374a"],
			contentsource: "markup", //"markup" or ["container_id", "path_to_menu_file"]
			arrowimages: {
				down:['downarrowclass', TEMPLATE_URL+'/img/down.png', 23],
				right:['rightarrowclass', TEMPLATE_URL+'/img/right.png']},
			transition: {overtime:300, outtime:600}, //duration of slide in/ out animation, in milliseconds
			shadow: {enable:false, offsetx:5, offsety:5}, //enable shadow?
			showhidedelay: {showdelay: 100, hidedelay: 200} //set delay in milliseconds before sub menus appear and disappear, respectively
		});
	}
	
	$('#months .month').bind('click',_monthClicked);
	$('.next-month').bind('click',_nextMonthClicked);
	$('.prev-month').bind('click',_prevMonthClicked);
	$months = $('#months .month');
	for(i=0;i<$months.length; i++){
		if($($months[i]).data('month') == _currMonth){
			$($months[i]).addClass('current');
		}
	}
	loadCalendar();
	
	
	// Bind an event to window.onhashchange that, when the hash changes, gets the
	// hash and adds the class "selected" to any matching nav link.
  $(window).hashchange(_hashChanged)
  
  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).hashchange();  
  
  
  $('.twocol').columnize({ columns: 2 });
  
	// Set up Header carousel
	_initCarousel();
	
	
	// Landing page
	if($('.landing-page').length > 0){
		_windowResize();
		$(window).resize(_windowResize);
	}

});

	var _currHeaderID			= 1,
	$headerPhotoDetailSection 	= null,
	$newHeaderPhoto				= null,
	$headerPhotoItems			= null,
	$headerLoadingIndicator		= null;
	var SCROLL_DUR				= 700,
	SCROLL_EASE					= 'easeInOutExpo',
	FADE_IN_EASE				= 'easeOutQuad',
	FADE_OUT_EASE				= 'easeOutQuad',
	FADE_IN_DUR					= 400,
	FADE_OUT_DUR				= 400,
	spinner						= null;
	headerSlideshowTimer		= null;
	
	//var _currMonth				= MONTH,
	//_currYear					= YEAR;
	

	// ------- Spinner for loading ------- //
	var spinnerOpts = {
	  lines: 10, // The number of lines to draw
	  length: 0, // The length of each line
	  width: 4, // The line thickness
	  radius: 11, // The radius of the inner circle
	  color: '#FFF', // #rgb or #rrggbb
	  speed: 1.4, // Rounds per second
	  trail: 31, // Afterglow percentage
	  shadow: false // Whether to render a shadow
	};
	
	function autoplayCarousel(){
		if(!_currHeaderID) _currHeaderID = 1;
		_currHeaderID++;
		if(_currHeaderID > $('.header-photos nav').children().length){
			_currHeaderID = 1;
		}
		_showHeaderPhoto();
	}

	function _initCarousel(){
		$headerPhotoItems 			= $('.header-photos nav a');
		$headerPhotoDetailSection	= $('#header-photo');
		
		var m = '<div id="loading-indicator"></div>';
		$headerLoadingIndicator = $(m);
		
		$headerPhotoDetailSection.append($headerLoadingIndicator);
		$headerLoadingIndicator.css('opacity',0);
		var target = document.getElementById('loading-indicator');
		
		spinner = new Spinner(spinnerOpts).spin(target);

			
		$(".header-photos nav a").removeAttr("href");
		$(".header-photos nav a").bind('click', _headerThumbClicked);
		
		headerSlideshowTimer = setTimeout ( "autoplayCarousel()", 5000 )
	}
	
	function _headerThumbClicked(e) {
		e.preventDefault();
		
		var $photoItem = $(e.currentTarget),
		isCurrent 		= $photoItem.hasClass('current'),
		img_id			= $photoItem.data('id');
		
		if(!isCurrent) {
			_currHeaderID = parseFloat(img_id);
			_showHeaderPhoto();
		}
	}
	
	function _showHeaderPhoto(){		
		if(_currHeaderID != '' && $('.header-photos nav').length > 0){
			clearTimeout(headerSlideshowTimer);
			headerSlideshowTimer = setTimeout ( "autoplayCarousel()", 5000 ); // reset the timer
			
			// Update highlights
			$headerPhotoItems.removeClass('current');
			$('.header-photos nav a[data-id="'+_currHeaderID+'"]').addClass('current');
			_displayHeaderPhotoheaderLoadingIndicator();
		}
	}
	
	function _displayHeaderPhotoheaderLoadingIndicator(){
		$headerLoadingIndicator.stop().animate({
			opacity: 1
		},  FADE_IN_DUR, FADE_IN_EASE);	
		_loadNewHeaderPhoto();
	}
	
	function _loadNewHeaderPhoto(){
		var newImage = new Image();
		$(newImage).attr('src', $('.header-photos nav a[data-id="'+_currHeaderID+'"]').data('src')).load(function () {
			
			// WHEN DONE LOADING THE IMAGE
			$('.header-photos .new_photo').addClass('old_photo').removeClass('new_photo');
			
			var m = '<div class="new_photo"></div>';
			$newHeaderPhoto = $(m)
			$headerPhotoDetailSection.append($newHeaderPhoto);
			
			$newHeaderPhoto.css({
				opacity: 0
			}).append(this);
			
			_windowResize();// make the new photo fit
			_displayNewHeaderPhoto();
		});
	}
	
	function _displayNewHeaderPhoto(){
		$headerLoadingIndicator.stop().animate({
			opacity: 0
		},  FADE_OUT_DUR, FADE_OUT_EASE);	
		$newHeaderPhoto.animate({
			opacity: 1
		}, FADE_OUT_DUR, FADE_OUT_EASE, _onDisplayNewHeaderPhotoComplete);		
	}
	
	function _onDisplayNewHeaderPhotoComplete(){
		$('.header-photos .old_photo').destroy();
	}
	
	
	function _nextMonthClicked(e){
		if(_currMonth < 12){
			_currMonth++;
		}else{
			_currMonth=1;
			_currYear++;
		}
		$months = $('#months .month');
		$months.removeClass('current');
		$('.widget_golfcompetitions > h1').html('Agenda '+_currYear);
		
		for(i=0;i<$months.length; i++){
			if($($months[i]).data('month') == _currMonth){
				$($months[i]).addClass('current');
			}
		}

		loadCalendar();
	}
	function _prevMonthClicked(e){
		if(_currMonth > 1){
			_currMonth--;
		}else{
			_currMonth=12;
			_currYear--;
		}
		$months = $('#months .month');
		$months.removeClass('current');
		$('.widget_golfcompetitions > h1').html('Agenda '+_currYear);
		
		for(i=0;i<$months.length; i++){
			if($($months[i]).data('month') == _currMonth){
				$($months[i]).addClass('current');
			}
		}

		loadCalendar();
	}
	function _monthClicked(e){
		e.preventDefault();
		var $target = $(e.currentTarget),
		isCurrent 		= $target.hasClass('current'),
		month			= $target.data('month');
		
		if(!isCurrent){
			$('#months .month').removeClass('current');
			$target.addClass('current');
			_currMonth	= month;
			loadCalendar();
		}
		
	}
	
	function loadCalendar(){
		
		$('#months .month').unbind('click',_monthClicked);
		$('.next-month').unbind('click',_nextMonthClicked);
		$('.prev-month').unbind('click',_prevMonthClicked);
		$('#calendar table .calendar_item td').hide(300,function(){
			$(this).parent().detach();
		});
		
			var loader = '<tr class="loading"><td colspan="3">Laden...</td></tr>';
			$loader = $(loader);
			
			$('#calendar table').append($loader);
			$loader.css({
			  display:'none'
			});
			
			
			$loader.delay(300).show(300,function(){
				$.ajax({
					url:BASE_URL+"/wp-admin/admin-ajax.php",
					type:'POST',
					data:'action=mgc_upcomingEvents&year='+_currYear+'&month='+_currMonth,
					success:function(data){
						$loader.hide(300,function(){
							$loader.detach();
							$('#calendar table').append(data);
							$('#months .month').bind('click',_monthClicked);
							$('.next-month').bind('click',_nextMonthClicked);
							$('.prev-month').bind('click',_prevMonthClicked);
						});
					}
				});
			});			

	}
	
	function _hashChanged(){
		var hash = location.hash;
		
		/*
			Set the E-Golf4U iFrame to the page 
			that is selected by the HASH in the URL
		*/
		if($('#egolf4u_iframe').length > 0 && (hash.replace( /^#/, ''))){
			$('#egolf4u_iframe').attr('src', 'http://'+EGOLF4U_ID+'.e-golf4u.nl/leden/iframe/'+hash.replace( /^#/, '' ));
			$('nav.menu .menu ul a').each(function(){
			var that = $(this);
			that[ that.attr( 'href' ).indexOf(hash) > -1 ? 'addClass' : 'removeClass' ]( 'selected' );
		});

		}
		// Iterate over all nav links, setting the "selected" class as-appropriate.

	}


	function _windowResize(){
		/*
			Do resize action for landing page
		*/
		if($('.landing-page').length > 0){
			$photoContainer		= $('#header-photo');
			$photo				= $('#header-photo .new_photo img');
			$contentContainer	= $('#content');
			$sidebar			= $('#sidebar');
			
			windowHeight 		= $(window).height();
			footerHeight		= $('#footer').innerHeight();
			photoHeight			= $photo.height();
			photoWidth			= $photo.width();
			topPosition			= $photoContainer.offset().top;
			photoContainerWidth = $photoContainer.innerWidth();
			
			if(windowHeight > footerHeight+topPosition+$contentContainer.innerHeight()+60){
				photoContainerHeight = (windowHeight-topPosition-footerHeight);
				$photoContainer.height(photoContainerHeight);
				$contentContainer.css('top',topPosition+((photoContainerHeight-$contentContainer.innerHeight())/2)+"px");
				$sidebar.css('top',topPosition+((photoContainerHeight-$sidebar.innerHeight())-30)+"px");
				
				if(photoContainerWidth <= (photoWidth*(photoContainerHeight/photoHeight))){
					$photo.height(photoContainerHeight);
					$photo.css('margin-left',"-"+(photoWidth*(photoContainerHeight/photoHeight)-photoContainerWidth)/2+"px");
					$photo.css('margin-top',"0px");
				}else{
					$photo.css('margin-top',"-"+(photoHeight-photoContainerHeight)/2+"px");
				}
			}
				
		}
	}

