$(document).ready(function(){
	// calendar navigation
	$('.calendar table .prevmonth, .calendar table .nextmonth').livequery('click', function(){
		$parent = $(this).parents('div.calendar')
		url = $(this).attr('href')
		$.ajax({
			type: "GET",
			url: url,
			success: function(response){
				$parent.html( $(response).html() );
			}
		});
		
		return false
	})
	
	//ipod
	$('.ipod').prepend('<p class="ipodvan">De iPod van</p>')
		
	// resize
	if($.cookie("css")) {
        $("#typeface").attr("href",$.cookie("css"));
    }	
	$("#resize a").click(function() {
        $("#typeface").attr("href",$(this).attr('rel'));
        $("#resize a").removeClass('current');
        $(this).addClass('current'); 
        $.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
        return false;
    });
	
    // Group Element as accordion
	function accordionChange(event, ui) {
		var $carousel = $('.carousel', ui.newContent)
		$('.carouselband li', $carousel).css('height','auto')
   		$('.carouselband li', $carousel).equalHeights().animate({opacity:1}, 1000, function(){
   			$('.carouselbandcontainer', $carousel).css('height', 'auto')
   		})

   		
   		//ui.oldContent // jQuery object, previous content
   		//ui.newHeader // jQuery object, activated header
   		//ui.oldHeader // jQuery object, previous header	  
   	}
	
    // tabs zijkant
    $('.nav-tabs2').livequery(function (){
        $(this).tabs();
    })
    
    $('#content ul.nav-tabs').each(function(){
		var parent = $(this).parent()
        $(this).tabs({
			load: function(event, ui) {
				$('.tabsPreload', parent).remove()
			}
        })
	})
	
    // MENU
    initMenu()

    /* even/odd */
    $('ul.striped li:odd, ol.striped li:odd').addClass('odd')
    $('ul.striped li:even, ol.striped li:even, table.striped tr:even').addClass('even')
    
    /* Bottom listing */
    makeColumn()

	$('#bottomnav li a').click(function(){
		$('#bottomlist').load($(this).attr('href'), callback)
		return false
	})
	
	function callback(response, status){
		if (status == 'success') {			
			makeColumn()
		}
	}
	
	function makeColumn(){
		if ( $('#bottomlist li.title').size() == 0 && $('#bottomnav li.current a span').html() == "Meest gelezen"){
			// add bottom subtitles
			var bottomTitle = new Array()
			bottomTitle['nl'] = ['Vandaag','Gisteren','Ouder']
			bottomTitle['fr'] = ["Aujourd'hui",'Hier','Plus anciens']
			bottomTitle['de'] = ['heute','gestern','�lter']
			bottomTitle['en'] = ['Today','Yesterday','Earlier']
	
			var lang = $('html').attr('lang')
				
			var bottomTitleArray = new Array()

			var today = $('#timestamp ins').attr('datetime')
			if (today != undefined){
				temp = today.split('T')
				today = parseDate(temp[0])

				var yesterday = parseDate(temp[0]);
				yesterday.setDate(today.getDate() - 1);
			}
			
			$('#bottomlist li:not(.title)').each(function(i){
				var nextItemDate = $('#bottomlist li:eq('+(i+1)+') ins').attr('datetime')
				var itemDate = $('ins', this).attr('datetime')
				
				if (nextItemDate != undefined){
					nextItemDate = nextItemDate.split('T')
					nextItemDate = parseDate(nextItemDate[0])
				}

				if (itemDate != undefined){
					itemDate = itemDate.split('T')
					itemDate = parseDate(itemDate[0])
				}
				
				if ( i == 0 && itemDate.toString() == today.toString() ){
					bottomTitleArray.push([(i-1),'<li class="title auto"><strong>'+bottomTitle[lang][0]+'</strong></li>'])
				}
 
				if ( i == 0 && itemDate.toString() == yesterday.toString() ){
					bottomTitleArray.push([(i-1),'<li class="title auto"><strong>'+bottomTitle[lang][1]+'</strong></li>'])
				}

				if ( i == 0 && itemDate < yesterday){
					bottomTitleArray.push([(i-1),'<li class="title auto"><strong>'+bottomTitle[lang][2]+'</strong></li>'])
				}
				
				if ( nextItemDate != undefined && itemDate.toString() == today.toString() && nextItemDate.toString() == yesterday.toString() ){
					bottomTitleArray.push([i,'<li class="title auto"><strong>'+bottomTitle[lang][1]+'</strong></li>'])
				}
				
				if ( nextItemDate != undefined && (itemDate.toString() == yesterday.toString() && nextItemDate.toString() != today.toString() && nextItemDate.toString() != yesterday.toString())
					|| (nextItemDate != undefined && itemDate.toString() == today.toString() && nextItemDate.toString() != today.toString() && nextItemDate.toString() != yesterday.toString()) ){
					bottomTitleArray.push([i,'<li class="title auto"><strong>'+bottomTitle[lang][2]+'</strong></li>'])
				}
			})

			for (var k = 0; k < bottomTitleArray.length; k++){
				$('#bottomlist li:not(.title):eq('+(bottomTitleArray[k][0]+1)+')').before(bottomTitleArray[k][1])
			}
			
		}
		
		$('#bottomlist').columnize({
			columns: 2,
			width: 280,
			height: 240
		
	    });
	}

	function parseDate(xmlDate)
	{
	      if (!/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/.test(xmlDate)) {
	           throw new RangeError("xmlDate must be in ISO-8601 format YYYY-MM-DD.");
	      }
	      return new Date(xmlDate.substring(0,4), xmlDate.substring(5,7)-1, xmlDate.substring(8,10));
	}
	
	$('table.sortable').livequery(function (){
		$(this).tablesorter({sortList:[[0,0]], widgets: ['zebra'], dateFormat: 'uk'});
	})
		
	$('table.sortable caption input').livequery('click', function(){
		var value = $("input[name='matchfilter']:checked").val()
		var table = $(this).parent().parent()
		
		$('tbody tr', table).css('display','')
		$('tbody tr', table).not('tr.'+value).css('display','none')
		
		$('tbody tr', table).removeClass('even')
		$('tbody tr', table).removeClass('odd')
		$('tbody tr:visible:even', table).addClass('even')
	})

	$('#content a.prev, #content a.next').livequery('click', function(){
		var div = $(this).parents('div:first')
		var url = $(this).attr('href')
		
		$.ajax({
			type: "GET",
			url: url,
			success: function(response){
				div.html( $(response).html() );
			}
		});

		return false
	})
	
	$('#content div.seasonoverview select').livequery('change', function(){
		var div = $(this).parent()
		var url = $(this).val()
		
		$.ajax({
			type: "GET",
			url: url,
			success: function(response){
				div.html( $(response).html() );
			}
		});
	})

	 /* jcarousel */
    $('#content div.facebook').jcarousel({'scroll': 2})
	
	/* klasse 'last' toevoegen bij laatste contentitem */
	// IE raar gedoe, doet 'addClass' niet
    // $('#main div.splitter div.col div.contentitem:last-child').addClass('last')
	$('#main div.splitter div.col div.contentitem:last-child').each(function(){
		$(this).attr('class', $(this).attr('class')+' last')
	})
		
	/* w en h van overlay div's parents setten [IE6] */
	$('#content div.video, #content div.audio, #content div.slideshow').each(function(){
		var w
		var h
		if ($('img', this).size() > 0){
			w = $('img', this).attr('width')+'px'
			h = $('img', this).attr('height')+'px'
		} else {			
			w = $(this).css('width')
			h = $(this).css('height')
		}
		$('.overlay', this).css({
			height: h,
			width: w
		})
	})

	/* Youtube overlay fix */
	$('embed').each(function(){
		if ($(this).attr('src').indexOf('youtube') >= 0){
			$(this).attr('wmode', 'transparent')
			$(this).parent().append('<param value="transparent" name="wmode"/>')
		}		
	})
	
	$('div.slideshow.embedded').livequery(function(){
		$(this).slideshow()
	})
	
	//sets and resets current state
	$('#bottomnav li a').click(function(){
		$(this).parent().siblings('.current').removeClass('current')
		$(this).parent().addClass('current')
	})
	
	$('.link a[href*="greybox"], a[rel*="greybox"]').livequery(function(){
		$(this).each(function(){
	        $(this).click(function(event){
	            event.preventDefault();
	            GB_show('', $(this).attr('href'), 396, 670);               
	        });
	    });
    });
    
    $('.slideshow:has(a.greybox)').livequery(function(){
    	$(this).each(function(){
			$(this).click(function(event){
				event.preventDefault();
				var href = $(this).find('a.greybox').attr('href');
				var t = '';
				GB_show(t, href, 396, 670);
				return false;                    
			});
		}); 
	});
	
	$('a.greybox').livequery(function(){
		$(this).click(function(event){
			event.preventDefault();
			var href = $(this).attr('href');
			var t = '';
			GB_show(t, href, 396, 670);
			return false;
		});
	});
	
	$('a[rel*="videoplayer"]').livequery(function(){
		$(this).each(function(){
	        $(this).click(function(event){
	            event.preventDefault();
	            openMediaPopupPlayer($(this).attr('href'),'',''); return false;               
	        });
	    });
    });
    
    $('a.permalinkInfo').livequery(function(){
		$(this).each(function(){
	        $(this).click(function(event){
	            event.preventDefault();
	            GB_show('', $(this).attr('rel'), 100, 400);               
	        });
	    });
    });
    
	// ads
	//if ( $('#imu img, #imu embed, #imu object').attr('src') != '' && $('#imu img, #imu embed, #imu object').size() > 0 ){
    if ($('#skyscraper').html() != null){
		$('#containercontainer').addClass('expand')
	}
	
	$('div.carousel').livequery(function(){
		$(this).each(function(){
			if ($(this).parents('.epg').size() > 0){
				$(this).epg()
			} else {
				$(this).carousel()
			}
		})
	})
	
	$('div.grid').gridHeight()
	$('div.grid li').each(function(){
		$(this).css('width', $('img',this).attr('width'))
	})
	
	$('div.ticker ol, div.ticker ul').ticker()
	
	/* AUDIO POPUP */
	$('li:not(.mediaItem).audio a, div.audio > h3 a, div.media.audio a, a[rel*=audioplayer]').livequery(function(){
		$(this).click(function(){
			try { pauseActiveFlash() }
			catch(e) {}
			
			var url = $(this).attr('href')
			if (url == "" || url == undefined || url == "#") url = $(this).attr('rel')
			audioWindow = window.open(url, "Audioplayer",'width=420,height=20,menubar=0,resizable=0,status=0,directories=0,scrollbars=0')
	
			if (window.focus){
				audioWindow.focus()
			}
			
			return false
		})
	})

	$("div.accordion div.section").each(function(){
		$(this).before('<h5>'+ $('h4', this).html() +'</h5>')
		$('h4', this).remove()
    })
	
	$("div.accordion.autoheight").accordion({ 
		header: "h5", selectedClass: 'open', event: 'click', autoHeight:true,
		change: function(event, ui) { accordionChange(event, ui) }
    })
    
    $("div.accordion:not(.autoheight)").accordion({ 
		header: "h5", selectedClass: 'open', event: 'click', autoHeight:false,
		change: function(event, ui) { accordionChange(event, ui) }
    })
    
    $('.grid.animate').each(function(){
		$this = $('li', this)
		$title = $('.title', this)
		height = $title.height()

		$title.css('bottom', '-'+height+'px')

		$this.hover(function(){
			$('.title', this).animate({
				bottom: '0px'
			}, 200)
		}, function(){
			$('.title', this).animate({
				bottom: '-'+($('.title', this).height())+'px'
			}, 200)
		})
	})
	
	$('#bottom .column:eq(2)').css('display', 'none')
})

function initMenu(){
    /* # jump vermijden */
    $('#topnav a').each(function(){
        //if ($(this).attr('href') == "#") $(this).attr('onClick', 'return false;')
    })

    /* alle submenu's verbergen */
    //$('#topnav ul.nav1 ul').hide()
	$('#topnav ul.nav3').hide()

    /* parents met style current op current zetten */
    $('#topnav ul.nav3, #topnav ul.nav2').each(function(){
        $parent = $(this).parent()
        if ( $('li', this).hasClass('current')){
            $parent.addClass('current')
        }
    })

    /* children van parent met style current weergeven */
    $('#topnav ul.nav1 > li.current, #topnav ul.nav2 > li.current').each(function(){
        $child = $('> ul', this)
        if ( $child.size() > 0){
            $child.show()    
        }
    })        

    /* hoogte verminderen/vermeerderen voor 3de menu */
    if ($('#topnav ul.nav2 > li.current').size() == 0 || $('#topnav ul.nav2 > li.current > ul').size() == 0){ 
        $('#topnav ul').css('height',cfg.topnav1+cfg.topnav2)
        $('#topnav li ul').css('height',cfg.topnav2)
    } else {
    	topnav3rows = (cfg.topnav3rows==0)?1:cfg.topnav3rows
        var rows = Math.ceil($('#topnav ul.nav2 > li.current ul.nav3 li').size() / topnav3rows);
        var offset = cfg.offset * rows

        $('#topnav ul').css('height',(cfg.topnav1+cfg.topnav2+offset)+'px')
        $('#topnav li ul').css('height',(cfg.topnav2+offset)+'px')
        $('#topnav li ul.nav3').css('height', offset+'px')
    }
}

function switchState($oldobj,$curobj){
	if ($curobj.attr('href') != "#" && $curobj.attr('onClick') == ""){
		$oldobj.removeClass('current')
		$curobj.addClass('current')
	}
}

function stripPX(s) {
    stripLength = s.length-2
    output = s.substring(0,stripLength)
    return output
}
