var DATE_HIDE_TIME = 150;
var SERMON_PLAYER_WIDTH = 450;

$(document).ready(function() {
	try{Typekit.load();} catch(e){}
	
	$('[placeholder]').placeholder();
	
	// menu
	$("#menu").children().hover(
		function () {
			//active_item = $(this).siblings('active');
			
			// set active link unactive
			$('a', $(this).siblings('.active')).css('background', '#fff');
			$('a', $(this).siblings('.active')).css('color', '#00AEEF');
						
			$('ul', this).fadeIn('fast');			
			$('a', this).css('color', '#fff');
		}, 
		function () {
			$('ul', this).hide();
			
			if (!$(this).hasClass('active'))
				$('a', this).css('color', '#00AEEF');
			
			// set active link active again
			$('a', $(this).siblings('.active')).css('background', '#00AEEF');
			$('a', $(this).siblings('.active')).css('color', '#fff');
		}
	);
		
	$("#home-content .header").children().hover(
		function () {
			active_item = $(this).siblings('.active');
			active_item.removeClass('active');
		}, 
		function () {
			active_item.addClass('active');
		}
	);
	
	$("#home-news-content").click(function() {
		loadContent('Functions', 'recent_news', 'latest-content', '');
		$(this).siblings('.active').removeClass('active');
		active_item = $(this);
		$("#home-news-content").addClass('active');
	});
	
	$("#home-blog-content").click(function() {
		loadContent('Functions', 'recent_blog', 'latest-content', '');
		$(this).siblings('.active').removeClass('active');
		active_item = $(this);
		$("#home-blog-content").addClass('active');
	});
	
	$("#home-teachings-content").click(function() {
		loadContent('Functions', 'latest_teachings', 'latest-content', '');
		$(this).siblings('.active').removeClass('active');
		active_item = $(this);
		$("#home-teachings-content").addClass('active');
	});
		
	$("#upcoming-events .item").hover(
		function () {
			// set popup
			popup = $('#upcoming-event-popup');
			
			var description = trim ($('.description', $(this)).html()); 
					
			if (description) {
				$('.text', popup).html( description );
			
				popup.show();
				popup.css('top',  $(this).position().top - 5);
			
				// set colors
				$(this).css('background', '#f3f3f3');
				$(this).css('cursor', 'pointer');
			}
		}, 
		function () {
			// set colors
			$(this).css('background', 'transparent');
			$(this).css('cursor', 'normal');
			
			popup.hide();
		}
	);	
	
	// Date selector in sidebar
	$('#date_browser .folder').click(function(e) {
		var icon = $('.icon', this),
			months = $(this).next('.months');
		if( !months.is(':hidden') ) {
			months.slideUp(DATE_HIDE_TIME);
			icon.html('+');
		} else {
			months.slideDown(DATE_HIDE_TIME);
			icon.html('-');
		}
		$('#date_browser .icon').not(icon).html('+');
		$('#date_browser .months').not(months).slideUp(DATE_HIDE_TIME);
	});
	
	$('.search_form a').click(function(e) {
		$(this).parent('form').submit();
	})
	$('.search_form').submit(function(e) {
		$('[placeholder]').placeholder('clear');
		location.href = $(this).attr('action') + encodeURI($('.searchfield', this).val());
		e.preventDefault();
	}); 
	
	//$('.newsletter').submit(function(e) {
	//	$('.newsletter').submit();
	//}); 
	$('.newsletter a').click(function(e) {
		$('[placeholder]').placeholder('clear');
		$(this).parent('form').submit();
	}); 
	
	$('#dik_login_button').click(function(e) {		
		$(this).parent('form').submit();
	})
	
	$('#dik_form_link').click(function(e) {
		$('#dik-login').fadeToggle();
	})
	
	var im = $('.lightbox_image');
	im.lightBox && im.lightBox();
});

function trim(value) {
	return value.replace(/^s+|s+$/,'');
}

function loadContent(klasse, functie, element, parameters) {	
	var url = 'ajax.php';
	var params = '?call=' + klasse + '/' + functie + '&' + parameters;
	var pos_x = ($("#" + element).width() / 2) - 32;
	var pos_y = ($("#" + element).height() / 2) - 32;
	
	$("#" + element + " > div").fadeTo(0, .3);
	
	bgcolor = $('#' + element).css('background-color');
	bgimage = $('#' + element).css('background-image');
	bgrepeat = $('#' + element).css('background-repeat');
	bgposition = $('#' + element).css('background-position');
	
	$('#' + element).css({background: "transparant url('images/ajax-loader.gif') no-repeat " + pos_x + "px " + pos_y + "px"});
	
	$.ajax({
	  	url: 'index.php' + params,
	  	async: false,
	  	success: function(data) {
			$("#" + element).html(data);
			$("#" + element + " > div").fadeTo(0, 1);
			
			//$('#' + element).css({background: "#fff"});
			$('#' + element).css('background-color', bgcolor);
			$('#' + element).css('background-image', bgimage);
			$('#' + element).css('background-repeat', bgrepeat);
			$('#' + element).css('background-position', bgposition);
	 	}
	});
}

function load_mp_player(id, title, speaker, soundfile, rowclass) {
	if (rowclass == 'even_row') bg_color = '#F3F2F2';
	else bg_color = '#F9F9F9';
	
	if ($('#' + id + '_row').is(":hidden")) {
		/* load flash player */
		if (soundfile != "") {							
			$('#' + id).flash( { 
				swf: 'js/player.swf',
				flashvars: {
					soundFile: soundfile,
					playerID: "'" + id + "'",
					quality: 'high',
					titles: title,  
					artists: speaker,  
					autostart: "no",
					animation: "no",
					encode: "no",
					bg: "fcfcfc", 				//Background
					leftbg: "f2f2f2", 			//Speaker icon/Volume control background
					lefticon: "007fca",			//Speaker icon
					voltrack: "d3d3d3",			//Volume track
					volslider: "007fca",		//Volume slider
					rightbg: "f2f2f2",			//Play/Pause button background
					rightbghover: "f2f2f2",		//Play/Pause button background (hover state)
					righticon: "1B7EB3",		//Play/Pause icon
					righticonhover: "30A5E8",	//Play/Pause icon (hover state)
					loader: "fba4a0",			//Loading bar
					track: "FFFFFF",			//Loading/Progress bar track backgrounds
					tracker: "eeeeee", 			//Progress track
					border: "CCCCCC",			//Progress bar border
					skip: "666666", 			//Previous/Next skip buttons
					text: "333333" 				//Text
				},
				width: SERMON_PLAYER_WIDTH,
				height: 34,
				wmode: 'transparent'
			}); 
			
			$('#' + id).show();
		}
		 
		$('#' + id + '_row').slideDown('medium', function() {});
		
		var intro = document.getElementById(id + '_intro');
		intro.style.display = 'none';
	} else {
		$('#' + id + '_row').slideUp('medium', function() {});
		$('#' + id).html('');
		
		var intro = document.getElementById(id + '_intro');
		intro.style.display = '';
	}
}

var SLIDE_TIME = 500, IMAGE_WIDTH = 420;

$(document).ready(function() {
	if ($('#slideshow_box').length != 0) {
		var current = 0,
			buttons = $('#slideshow-buttons a'),
			unfocus = function(e) {
				$(this).blur();
			},
			select = function(i) {
				$('#slideshow_box').animate({left: i * -IMAGE_WIDTH}, SLIDE_TIME);
				buttons.not($(buttons[current = i]).addClass('active')).removeClass('active');
			}; 
		
		$('#slideshow .item_list, #slideshow_box').width(IMAGE_WIDTH * buttons.length);
		buttons.focus(unfocus).each(function(i) {
			$(this).click(function(e) {
				i != current && select(i);
				e.preventDefault();
			});
		});
			
		
		setInterval ( "automateSlide()", 4000 );
	}
});

function automateSlide() {
		var left_pos = 0,
			nr_of_slides = $("#slideshow_box > div.item").size(),
			position = $('#slideshow_box').position();
			//cur_slide = position.left / IMAGE_WIDTH,
			//buttons = $('#slideshow-buttons a');
  		
		// set buttons
		//buttons.not($(buttons[current = cur_slide]).addClass('active')).removeClass('active');
		
		var $active = $('#slideshow-buttons a.active');
		var $next = $active.next();    
	
		if($next.length == 0) $('#slideshow-buttons a:first').addClass('active');
		else $next.addClass('active');
		
		$active.removeClass('active');  
			
		// set to first slide on last slide
		if (position.left == ((nr_of_slides-1) * -IMAGE_WIDTH)) left_pos = 0;
		else left_pos = position.left - IMAGE_WIDTH;
		
		// move the slide		
		$('#slideshow_box').animate({left: left_pos}, SLIDE_TIME);
	}

var MONTH_TEXT = {
		1: ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni',
			'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December'],
		2: ['January', 'February', 'March', 'April', 'May', 'June',
			'July', 'August', 'September', 'October', 'November', 'December']
	},
	DAY_TEXT = {
		1: ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'],
		2: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
	},
	MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
	CELL_WIDTH = 37, CELL_HEIGHT = 37, OFFSET_TOP = 40, OFFSET_LEFT = 20;

$(document).ready(function() {
	var json_decode = function(str) {
			return typeof $.parseJSON == 'function' ? $.parseJSON(str)
				: (str ? eval('(' + str + ')') : {});
		},
		active_screen = $('#calendar_active'),
		cells = $('#calendar-widget .cells').children(),
		lang = parseInt($('#calendar_data input[name=language]').val()) || 2,
		current_year = parseInt($('#calendar_data input[name=year]').val()),
		current_month = parseInt($('#calendar_data input[name=month]').val()),
		data = json_decode($('#calendar_events').html()),
		corner_left = $('#calendar-widget .corner_left'),
		corner_right = $('#calendar-widget .corner_right'),
		year_month_text = $('#calendar-widget .month a'),
		today_date = new Date(),
		today = [today_date.getFullYear(), today_date.getMonth() + 1, today_date.getDate()],
		load_items = function(day, month, year) {
			day = String(day);
			month = String(month);
			year = String(year);
			if( year in data && month in data[year] && day in data[year][month] )
				return data[year][month][day];
			else
				return ['Fout', 'Data kon niet worden geladen.', ''];
		},
		click_counter = 0,
		hide_active_screen = function() {
			click_counter++ && active_screen.hide();
		},
		add_month_and_year = function(month, year, add) {
			month += add;
			
			if( !month ) {
				month = 12;
				year--;
			} else if( month == 13 ) {
				month = 1;
				year++;
			}
			
			return [month, year];
		},
		json_merge = function(a, b) {
			for( var i in b )
				a[i] = (i in a && typeof(a[i]) == 'object') ? json_merge(a[i], b[i]) : b[i];
			
			return a;
		},
		event_click_event = function(e) {
			var elem = $(this), cell = elem.closest('.cell'),
				before = cell.prevAll().length,
				row = Math.floor(before / 7), column = before % 7,
				day = parseInt(elem.html()),
				added = add_month_and_year(current_month, current_year,
					cell.hasClass('next_month') || -cell.hasClass('previous_month')),
				selected_date = DAY_TEXT[lang][column] + ' ' + day + ' ' + MONTH_TEXT[lang][added[0] - 1],
				items = load_items(day, added[0], added[1]),
				$desc = $('.description', active_screen).html(items[0][1].replace(/\r?\n/g, '<br />'));;
			
			$('.title', active_screen).html(items[0][0]);
			$('.location span', active_screen).html(items[0][2]);
			$('.date span', active_screen).text(selected_date);
			$('.time span', active_screen).text(items[0][3]);
			
			// Add "Read more" link to description
			items[0][4].length && $desc.append(' <a href="' + items[0][4] + '" target="_blank" class="read-more">&#187; Read more</a>');
			
			$.each(items.slice(1), function(i, item) {
				var $tpl = $('#calendar_item_template').clone().attr('id', '').appendTo($desc),
					desc = item[1].replace(/\r?\n/g, '<br />');
				
				// Add "Read more" link to description
				if( item[4].length )
					desc += ' <a href="' + item[4] + '" target="_blank" class="read-more">&#187; Read more</a>';
				
				if( desc.length )
					$tpl.find('.tpl_description').html(desc);
				else
					$tpl.find('.tpl_description').remove();
				
				$tpl.find('.tpl_title').html(item[0]);
				$tpl.find('.tpl_location span').html(item[2]);
				$tpl.find('.tpl_date span').text(selected_date);
				$tpl.find('.tpl_time span').text(item[3]);
			});
			
			active_screen.css({
				top: row * CELL_HEIGHT + OFFSET_TOP,
				left: column * CELL_WIDTH + OFFSET_LEFT
			});
			click_counter = 0;
			active_screen.show();
			
			e.preventDefault();
		},
		unfocus = function(e) {
			$(this).blur();
		},
		bind_events = function() {
			$('#calendar-widget .event a')
				.click(event_click_event)
				.focus(unfocus);
		},
		update_cell_numbers = function() {
			// Unbind previous events
			$('#calendar-widget .event a').unbind('click', event_click_event);
			
			// Get cell arrangement
			var before = new Date(current_year, current_month - 1, 1).getDay(),
				days = MONTH_DAYS[current_month - 1],
				prev_month_days = MONTH_DAYS[(current_month + 10) % 12];
			
			for( var i = 0; i < 35; i++ ) {
				cell = $(cells[i]).attr('class', 'cell');
				year = current_year;
				month = current_month;
				if( i < before ) {
					cell.addClass('previous_month');
					day = prev_month_days - before + i + 1;
					added = add_month_and_year(month, year, -1);
				} else if( i < before + days ) {
					day = (days + i - before) % days + 1
					added = false;
				} else {
					day = i - before - days + 1;
					cell.addClass('next_month');
					added = add_month_and_year(month, year, 1);
				}
				if( added != false ) {
					month = added[0];
					year = added[1];
				}
				
				cell.html(day);
				
				if( year == today[0] && month == today[1]  && day == today[2] )
					cell.addClass('today');
			}
			
			if( $(cells[28]).hasClass('today') ) {
				corner_left.addClass('today');
			} else {
				corner_left.removeClass('today');
				if( $(cells[34]).hasClass('today') )
					corner_right.addClass('today');
				else
					corner_right.removeClass('today');
			}
			
			bind_events();
		},
		update_cell_events = function() {
			// Unbind previous events
			$('#calendar-widget .event a').unbind('click', event_click_event);
			
			// Get cell arrangement
			var before = new Date(current_year, current_month - 1, 1).getDay(),
				days = MONTH_DAYS[current_month - 1],
				prev_month_days = MONTH_DAYS[(current_month + 10) % 12];
			
			for( var i = 0; i < 35; i++ ) {
				cell = $(cells[i]);
				year = current_year;
				month = current_month;
				if( i < before ) {
					day = prev_month_days - before + i + 1;
					added = add_month_and_year(month, year, -1);
				} else if( i < before + days ) {
					day = (days + i - before) % days + 1
					added = false;
				} else {
					day = i - before - days + 1;
					added = add_month_and_year(month, year, 1);
				}
				if( added != false ) {
					month = added[0];
					year = added[1];
				}
				if( data[year] && data[year][month] && data[year][month][day] ) {
					cell.addClass('event');
					cell.html('<a href="javascript:void(0);">' + cell.html() + '</a>');
				}
			}
			
			bind_events();
		},
		select_month = function(amount) {
			// Update current month/year text
			added = add_month_and_year(current_month, current_year, amount);
			var load_year = current_year = added[1], load_month = current_month = added[0];
			year_month_text
				.attr('href', 'calendar/' + current_year + '/' + current_month)
				.text(MONTH_TEXT[lang][current_month - 1] + ' ' + current_year);
			update_cell_numbers();
			
			// Load month events
			// TODO: implement the URL below
			if( !(current_year in data && current_month in data[current_year]) ) {
				$.ajax({
					url: '/calendar/data',
					async: true,
					data: {year: current_year, month: current_month},
					success: function(new_data) {
						data = json_merge(data, new_data);
						if( current_month == load_month && current_year == load_year )
							update_cell_events();
					},
					dataType: 'json'
				});
			} else {
				update_cell_events();
			}
		};
	
	// Events
	bind_events();
	
	// Popup
	$(document).click(hide_active_screen);
	$('.date, .title, .content, .bottom', active_screen).click(function(e) {
		click_counter = 0;
	});
	
	// Next/previous month
	$('#calendar-widget .arrow_left').focus(unfocus).click(function(e) {
		select_month(-1);
	});
	$('#calendar-widget .arrow_right').focus(unfocus).click(function(e) {
		select_month(1);
	});
});
