var searchOpen=false;
$(document).ready(function(e) {
	$('.djbroadcastfm').click(function() { window.open('http://www.djbroadcast.fm/popup.html','djbroadcastfm','status=0,toolbar=0,scrollbar=0,resizable=0,width=346,height=420'); });
	$('.search FORM').live('click', function(e) {
		if (!searchOpen) {
			$('.search INPUT').css('display','block');
			$('.search INPUT').width(1);
			$('.search INPUT').focus();
			$('.search INPUT').animate({width:150});
			$('.search').animate({backgroundColor:'#6d6d6d'},700);
			$('#submit-search').fadeOut(700,function(){$(this).css({backgroundImage:'none'});$(this).show();});
			searchOpen=true;
		}
		//simple validation
		var currentVal = ($('#search-field').val()) ? true : false; 
		if(currentVal && searchOpen){
			$('#searchForm').submit();
		} else {
			return false;
		}
		e.preventDefault();
	});
	/* Partyshots slider */
	/* Set thumbnail container width for slider and give images a number to relate thumb clicks to photo */
	w=0; // width
	i=1; // increment
	$('.thumbnails .container').children('A').each(function() {
		$(this).attr('rel',i);
		i++;
		w=w+($(this).outerWidth(true)+3.5);
	});
	i=1;
	$('#images img').each(function() {
		$(this).attr('rel',i);
		i++;
	});
	$('.thumbnails .container').width(w);
	/* link clicks in partyshots */
	$('.thumbnails .container a').css('cursor','pointer');
	$('.thumbnails .container a').click(function(e){
		e.preventDefault();
		$('#images img').hide().removeClass('theShot');
		$('.thumbnails img').show();
		$('#images img[rel="'+$(this).attr('rel')+'"]').show().addClass('theShot').click().focus(); // make sure scrollpane doesn't get focus when clicking on an image
		$('.scroll-pane').blur();
	});
	$('.thumbnails .container a').eq(0).click();
	/* prevnext buttons */
	$("#but_prev").show();
	$("#but_next").show();
	/*	Moved to stomp-script with extra interaction
	function nextSlide() {
		var img = parseInt($('.theShot').attr('rel'));
		$('.theShot').removeClass('theShot');
		img++;
		if (img > $('#images img').length) img = 1;
		$('#images img').hide();
		$('.thumbnails img').show();
		$('#images img[rel="'+img+'"]').show().addClass('theShot');	
	}
	function prevSlide() {
		var img = parseInt($('.theShot').attr('rel'));
		$('.theShot').removeClass('theShot');
		img--;
		if (img < 1) img = $('#images img').length;
		$('#images img').hide();
		$('.thumbnails img').show();
		$('#images img[rel="'+img+'"]').show().addClass('theShot');	
	}*/
	/*
	$("#but_prev").click(function(){
		prevSlide();
	});
	$("#but_next").click(function(){
		nextSlide();
	});	
	*/
	/* Set the slider */
	$('.scroll-pane').jScrollPane();
	moreClickable();
	/* Matthijs */
	bindVideo();
	/* Commentbox behaviour */
	$("#docomment").click(function(){
        $.blockUI({message: $('#commentbox'),
			overlayCSS:{cursor:'auto',background:'#191312;',opacity:0.5},
			css:{textAlign:'left',border: '0px solid',top:'10%',cursor:'auto',width:'322px',height:'auto',background:'#000',paddingRight:'8px',opacity:1}
		});
		getRidOfFlash();
		$(".blockOverlay,#closecomment,#closecomment2").click(function(){$.unblockUI({onUnblock:function(){$('#videobox .video').html('');}});getMyFlashBack();});
		$("#postcomment").click(function(){$("#reactionform").submit();});
		$('#reaction_email').attr('name','tahr');
	});
	if ($('#commentbox input.error,#commentbox textarea.error,#commentbox p.error').length > 0) $("#docomment").click();
	/* Activate loadmore button on a page if JS is on */
	/* now enabled from within stomp-script.js */
	//enableLoadMore();
	/* Load more button behaviour */
	loadMore();
	/* Related and popular tabs behavious */
	if ($("#popularbutton").length > 0) showPopular();
	$("#relatedbutton").click(function(){showRelated();});
	$("#popularbutton").click(function(){showPopular();});
	/* Google maps */
	if ($("#map_canvas").length > 0) {initialize_gmaps();}
	/* Split image for reviews */
	//var s=$('.review IMG').attr('src');
	//$('.review').html('<div class="review2"><div><img src="'+s+'" alt=""><img src="'+s+'" alt=""><img src="'+s+'" alt=""></div></div>');
	//$('.review2').scrollLeft(173);
	/* comment cloud */
	$('.commentcount').each(function (index,element) {
		val = makeCommentCountAwesome($(this).html());
		$(this).html(val);
		$(this).addClass('done');
	});
	/* Protect blockui from flashembeds */
	$('object,embed,iframe').not('object embed').wrap('<div class="blockUIEmbeds"></div>');
	$('.blockUIEmbeds').wrap('<div class="blockUIEmbedsWrapper"></div>');
	/* Make external links in articles open in new window */
	$(".left a[href^='http:']:not([href*='" + window.location.host + "'])").each(function() {               
        $(this).attr("target", "_blank");
    });
});
/* Matthijs */
/* Make comment counter cloud look better */
function makeCommentCountAwesome(val) {
	val = val.replace(/1/g,'<span class="number1">&nbsp;</span>');
	val = val.replace(/2/g,'<span class="number2">&nbsp;</span>');
	val = val.replace(/3/g,'<span class="number3">&nbsp;</span>');
	val = val.replace(/4/g,'<span class="number4">&nbsp;</span>');
	val = val.replace(/5/g,'<span class="number5">&nbsp;</span>');
	val = val.replace(/6/g,'<span class="number6">&nbsp;</span>');
	val = val.replace(/7/g,'<span class="number7">&nbsp;</span>');
	val = val.replace(/8/g,'<span class="number8">&nbsp;</span>');
	val = val.replace(/9/g,'<span class="number9">&nbsp;</span>');
	val = val.replace(/0/g,'<span class="number0">&nbsp;</span>');
	return val;
}
/* Dynamic assignment of load more button */
loadSession = 0; 
function loadMore() {
	// when load more is clicked
	$(".loadmore").one("click", function(e){
		e.preventDefault();
		// get the page, url and target
		var page = parseInt($(".loadmore").attr('rel'));
		var target = $(".loadmore").attr('target');
		var ajaxUrl = $(".loadmore").attr('href');
		// remove the button from DOM
		$(".loadmore").hide().remove();
		// do the request if allowed
		$.ajax({
			url: ajaxUrl,
			cache: false,
			success: function(data) {
				// display data and update pagecounter
				if (data != '') {
					loadSession++;
					$(target).append($(data).addClass('postLoaded' + loadSession)); //add class postLoaded to the objects within the data
					$('.commentcount').each(function (index,element) {
						if (!$(this).hasClass('done')) {
							var val = makeCommentCountAwesome($(this).html());
							$(this).html(val);
							$(this).addClass('done');
						}
					});

					
					//fakelazyload teh postloaded articles
					$('.postLoaded' + loadSession).fakelazyload({
						loadSpeed: 400,
						animationSpeed: 600
					});
					
					$(".loadmore").fadeIn(700);
					loadMore();
					moreClickable();
					enableLoadMore();
					bindVideo();
				}
			}
		});
	});
}
/* Make comments more clickable */
function moreClickable() {
	$('.comments DIV, .related DIV, .hoverArticle, #testlab_main .item').hover(function(){
		$(this).css('cursor','pointer');
	});
	/*$('.comments DIV, .related DIV, .hoverArticle, #testlab_main .item').delegate(':not(span.author *,span.author, .socialButton, .socialButton *)','click', 
		function () {
			document.location=$(this).find('A').attr('href');
			return false;
		}
	);*/
	$('.comments DIV, .related DIV, #testlab_main .item').click(function(e) {
		document.location=$(this).find('A').attr('href');
		return false;
	});
	$('.hoverArticle').click(function(e) {
		if (!$(e.target).is('span.author,span.author div,span.auther img,span.auther h4,span.author a,.socialButton,.socialButtons')) {
			document.location=$(this).find('A').attr('href');
			return false;
		}
	});
}
/* Activate loadmore button on a page if JS is on */
function enableLoadMore() {
	if ($(".loadmore").length > 0) {
		$(".loadmore").show();
		$(".loadmore").attr('href',$(".loadmore").attr('href').substring(0,$(".loadmore").attr('href').lastIndexOf('/')+1)+'update.html');
	}
}
/* Show related items */
function showRelated() {
	$(".relateditem").show();
	$(".popularitem").hide();
	$("#relatedbutton").addClass('active');
	$("#popularbutton").removeClass('active');
}
function showPopular() {
	$(".relateditem").hide();
	$(".popularitem").show();
	$("#relatedbutton").removeClass('active');
	$("#popularbutton").addClass('active');
}
/* Google maps Info window behaviour */
var infowindow;
var map;
var markers = [];
/* Google maps initialization */
function initialize_gmaps() {
	infowindow = new google.maps.InfoWindow();
	map = new google.maps.Map(
		document.getElementById("map_canvas"),
		{
			zoom: 7,
			center: new google.maps.LatLng(52.133488,5.29541),
			mapTypeId: google.maps.MapTypeId.HYBRID
		}
	);
	$.get('/magazine/markers.xml', {}, function(xml) {
		$('marker',xml).each(function(i) {
			var iconprops = makeIcon('/img/djbmarker.png',21,24);
			var marker = new google.maps.Marker({
				title: $(this).attr('name'),
				map: map,
				clickable: true,
				position: new google.maps.LatLng(
				   parseFloat($(this).attr('lat')),
				   parseFloat($(this).attr('lng'))
				),
				description: '<b>'+$(this).attr('name')+'</b><br />'+$(this).attr('address')+'<br>'+$(this).attr('city'),
				icon: iconprops.image
			});
			google.maps.event.addListener(marker, 'click',function() {
				infowindow.close();
				infowindow.setContent(marker.description);
				infowindow.open(map, marker);
			});
			markers.push(marker);
		});
		var styles = [{
			url: '/img/djbclustermarker.png',
			height: 33,
			width: 21,
			textColor: '#fff',
			textSize: 9,
			anchor: [18,0],
			anchorIcon: [0,4],
			fontFamily: 'Arial, sans-serif'
		  },
		  {
			url: '/img/djbclustermarker.png',
			height: 33,
			width: 21,
			textColor: '#fff',
			textSize: 9,
			anchor: [18,0],
			anchorIcon: [0,4],
			fontFamily: 'Arial, sans-serif'
		  },
		  {
			url: '/img/djbclustermarker.png',
			height: 33,
			width: 21,
			textColor: '#fff',
			textSize: 9,
			anchor: [18,0],
			anchorIcon: [0,4],
			fontFamily: 'Arial, sans-serif'
		  }];
		var mc = new MarkerClusterer(map, markers, {styles: styles,gridSize: 30, maxZoom: 13});
	});
}
function makeIcon (image, width, height) {
	var image = new google.maps.MarkerImage(image,
	// This marker is 20 pixels wide by 32 pixels tall.
	new google.maps.Size(width, height),
	// The origin for this image is 0,0.
	new google.maps.Point(0,0),
	// The anchor for this image is the base of the flagpole at 0,32.
	new google.maps.Point(width/2, height));
	/*var shadow = new google.maps.MarkerImage('img/shadow-marker.png',
	// The shadow image is larger in the horizontal dimension
	// while the position and offset are the same as for the main image.
	new google.maps.Size(38, 34),
	new google.maps.Point(0,0),
	new google.maps.Point(20, 25));*/
	// Shapes define the clickable region of the icon.
	// The type defines an HTML <area> element 'poly' which
	// traces out a polygon as a series of X,Y points. The final
	// coordinate closes the poly by connecting to the first
	// coordinate.
	var icon  = {'image':image/*,'shadow':shadow*/};
	return icon;
}

function bindVideo() {
	/* Prevent double binding */
	//$('.videoButton').unbind();
	/* Place video buttons if someone has JS */
	$('.videoButton').each(function(i,el) {
		img = $(this).parent().find('img');
		$(this).show().css({top : ((img.height()/2)-18)+'px',left : ((img.width()/2)-21)+'px',position: 'absolute'});
	});
	/* Create video box if visitor has JS */
	if ($('.videoButton,.bannerButton').length > 0) {$('body').append('<div id="videobox"><div class="close" id="closecomment2">&nbsp;</div><div class="logo">&nbsp;</div><div class="video ajaxloader"></div></div>');}
	/* video overlay behaviour */
	$('.videoButton,.bannerButton').click(function(e){
		$('.video').addClass('ajaxloader');
		e.stopPropagation();
		e.preventDefault();
		$('#videobox .video').html('<iframe src="'+$(this).attr('video-url')+'" width="800" height="450" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>');
		var w=($(window).width()-$('#videobox').width())/2-10;
		var h=($(window).height()-$('#videobox').height())/2-10;
		$.blockUI({message: $('#videobox'),
			overlayCSS:{cursor:'auto',background:'#000;',opacity:1},
			css:{textAlign:'left',border: '0px none',top:h,cursor:'auto',width:'820px',height:'auto',left:w,opacity:1,background:'#000'}
		});
		getRidOfFlash();
		$(".blockOverlay,#closecomment,#closecomment2").click(function(){$('.video').removeClass('ajaxloader');$.unblockUI({onUnblock:function(){$('#videobox .video').html('');}});getMyFlashBack();$('#videobox .video').html('');});
	});
}
/* Move flash from viewport for BlockUI */
function getRidOfFlash() {
	$('.blockUIEmbedsWrapper').each(function() {
		$(this).height($(this).height()); // fix the height when we start hiding stuff.			
	});
	$('.blockUIEmbeds').hide();
}
function getMyFlashBack() {
	$(".blockUIEmbeds").show();
}
