/*

*/

function initAgenda()
{

	var IE = (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) ? 0 : 1;

	$(".agenda .info").hide();
	$(".agenda .toevoegen a").click(

		function()

		{

			var checkElement = $(this).parent().parent().next();

									

			if ( checkElement.is("tr") && checkElement.is(":visible") )

			{

				$(this).removeClass("collapse");				

				

				if ( IE )

				{

					checkElement.hide()

				} else {

					checkElement.slideUp(800);

				}

				

			} else {

			

				$(this).addClass("collapse");

				

				if ( IE )

				{

					checkElement.show();

				} else {

					checkElement.slideDown(800);

				}

				

			}

			

			return false;

		}

	);

}

/*
	fontgroote veranderen en laatste aanpassing bewaren in cookie
*/
function initFontSizer()
{

	var stylesheet = "big.css";

	var fs = document.getElementById('fontsizer');
	
	if ( !fs ) return;
	
	var btns = fs.getElementsByTagName('a');
	
	var cookieName = "isLarge";
	
	disableStyleSheet("large", true);
	
	var isLarge = readCookie( cookieName ) || 0;
	
	if ( isLarge == 1 ) disableStyleSheet("large", false );
	
	var smaller = btns[0];
	var bigger = btns[1];
	
	
	smaller.onclick = function()
	{
		disableStyleSheet("large", true);
		
		createCookie( cookieName, 0, 365 );
		
		//return false;
	}

	bigger.onclick = function()
	{
		disableStyleSheet("large", false );
		
		createCookie( cookieName, 1, 365);
		
		//return false;
	}
}
function disableStyleSheet(title, disabled )
{
	var links = document.getElementsByTagName("link");
	
	for( var i = 0; i < links.length; i++)
	{
		var a = links[i];
		if( a.getAttribute("title") && a.getAttribute("title") == title ) 
		{
			// alert( disabled );
			a.disabled = disabled;
		}
	}
}


/*
	cookies
*/
function createCookie(name, value, days )

{

	if ( days )

	{

		var date = new Date();

		date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );

		var expires = "; expires=" + date.toGMTString();

	} else {

	

		var expires = "";

	}

	

	document.cookie = name + "=" + value + expires + "; path=/";

}
function readCookie( name )

{

	var nameEQ = name + "=";

	var ca = document.cookie.split(";");

	

	for( var i = 0; i < ca.length; i++)

	{

		var c = ca[i];

		while( c.charAt(0) == " " ) c = c.substring( 1, c.length );

		if ( c.indexOf(nameEQ) == 0 ) return c.substring( nameEQ.length, c.length );

	}

	

	return null;

}
function eraseCookie(name)

{

	createCookie(name, "", -1);

}
/*

	

*/
function initCarousel()

{

	function changeTab()
	{
		var index = this.id.split("_")[1] || 0;

				

		$("#news-cycler li a").each(

			function(i,val)

			{

				if ( i == index )

				{

					$(this).addClass("active");

				} else {

					$(this).removeClass("active");

				}

			}

		);		

	}
	
	$(".download-cycler .item").click(
		function(e)
		{
			var href = $(this).find('a').attr('href') || "";
			
			if ( href.length > 1 )
			{
				document.location.href = href;
			}
			
			e.preventDefault();
		}
	);

	

	$(

		function()

		{

			$('#news-cycler .news-items').cycle(

				{

					timeout: 5000,

					speed: 1000,

					before: changeTab

				}

			);

		}

	);

}

function initDropShadows()
{

	var headings = $('.shadow');	

	headings.each(

		function()
		{

			var txt = $(this).text();

			var span = $("<span></span>");
			
			span.text(txt);

			var schaduw = span.clone();

			schaduw.css({ top: "10px", left: "12px", color: "#000"});


			$(this).html("");
			$(this).append(schaduw);
			$(this).append(span);
		}
	);

}

$( document ).ready( 

	function() {

		initAgenda();
		initFontSizer();
		initSearchBox();
		initCarousel();
		initAlbumScroller();
		initAlbumSecondaryScroller();
		initHiliteBlocks();		
		initDropShadows();		
		initTrackList();
		initPopup();
		initExternalLinks();
		
		initViewstacks();

		var currentPage = location.href;
		var currentPage = currentPage.split('/');
		var currentPage = currentPage[4];
		
		var searchStr = location.href;
		var searchStr = searchStr.split('/');
		var searchStr = searchStr[5];
		
		if (currentPage == "search") {
			initSearch(searchStr);
		}
		
		$('.photo-album a').lightBox();
		$('.latest-photo-album a').lightBox();	
		$('.photo-album-teaser a').lightBox();			


	}

);


function initViewstacks()
{
	/*
		.viewstack
			.tabs
				li -> .view
				li -> .view
				li -> .view			
		
	*/
	
	var tabs = $(".viewstack .tabs a");
	$(".viewstack .view:gt(0)").hide();
	
	tabs.each(
		
		function(i)
		{
			$(this).click(
			
				function(e)
				{
					$(".viewstack .tabs .active").removeClass("active");
					
					$(this).addClass("active");
					
					$(".viewstack .view").hide();
					$(".viewstack .view:eq(" + i + ")").show();
					
					e.preventDefault();
				}
			);
		}
	);
}


/*

	initialiseren miniplayertjes downloadshop en id's opslaan in array.

	in flash wordt stopAudioItems aangeroepen en bevind zich een callback voor stopAudio

	zodat tracks niet door elkaar heen spelen

*/
var audioItems = new Array();
function initTrackList()

{

	$(".playlist a.audio").each(

	

		function(i)

		{

			var id = 'audioItem' + i;

			

			audioItems.push(id);

			

			$(this).attr( {id: id})

			

			var mp3 = escape( $(this).attr("href") );

			

			var flashvars = { mp3: mp3 };

			var params = { wmode: "transparent" };

			var attributes = {};

					

			swfobject.embedSWF("/static/flash/miniplayer.swf", id, "16", "17", "9.0.0", "static/flash/expressInstall.swf", flashvars, params, attributes );

		}

	

	);

	

}
/* wordt aangeroepen vanuit flash */

function stopAudioItems()

{

	for( var i = 0; i < audioItems.length; i++)

	{

		MM_findObj( audioItems[i] ).stopAudio();

	}

}
/*

	omdat getElementById niet werkt met externalinterface

*/

function MM_findObj(n, d) { //v3.0

  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {

    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}

  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];

  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;

}
/*

	behaviour vierkante actieblokjes

*/

function initHiliteBlocks()

{

	var hilites = $(".hilite");

	

	hilites.mouseover(

	

		function()

		{

			$(this).addClass("over");

		}

	);

	

	hilites.mouseout(

	

		function()

		{

			$(this).removeClass("over");

		}

	);

	

	hilites.click(

	

		function()

		{

			var url = $(this).find("a.details").attr("href");

			

			if (url) document.location.href = url;

		}

	);	

}

/*

	jcarousel albumblokjes

*/
function albumScrollerNav(carousel)

{

	jQuery('.albums-right').bind('click', function() {

        carousel.next();

        return false;

    });
    jQuery('.albums-left').bind('click', function() {

        carousel.prev();

        return false;

    });

}
function initAlbumScroller()

{

	$("#album-carousel").jcarousel(

		{

			scroll: 1,

			buttonNextHTML: null,

			buttonPrevHTML: null,

			visible: 5,

			animation: "slow",

			initCallback : albumScrollerNav

		}

	);	

}
function albumScrollerSecondaryNav(carousel)

{

	jQuery('.albums-secondary-right').bind('click', function() {

        carousel.next();

        return false;

    });
    jQuery('.albums-secondary-left').bind('click', function() {

        carousel.prev();

        return false;

    });

}
function initAlbumSecondaryScroller()

{

	$("#album-secondary-carousel").jcarousel(

		{

			scroll: 1,

			buttonNextHTML: null,

			buttonPrevHTML: null,

			visible: 5,

			animation: "slow",


			initCallback : albumScrollerSecondaryNav

		}

	);	

}
function jcarousel_initCallback(carousel)

{	

	var btns = $(".resultsnav .carouselbutton");

	

	btns.bind(

		

		"click",

		function()

		{

			btns.each(

				function()

				{

					$(this).removeClass("active");

				}

			);

			

			var i = parseInt( this.rel );

			

			carousel.scroll( i );

			

			$(this).addClass("active");

			

			

			return false;

		}

	);

	

	carousel.scroll( 1 );

}

var numToReturn = 6;
var numReturned = 0;

/*
	xml zoekresultaten omzetten naar dom-objecten
*/	
function convertXML(xml) {

	var xmlResults = $(xml).find("result");
	var numResults = xmlResults.size();
	var trefwoord = $(xml).find("results").attr("match");
	var searchtype = $(xml).find("results").attr("type");
	
	if (searchtype == "magazine" || searchtype == "agenda" || searchtype == "video") {
	
		var dl = $("#magvid");
		
	} else {
	
		var dl = $("#"+searchtype);
		
	}
	
	
	numReturned++;
	
	if ( numResults > 0) {

		var xmlResultsSets = $(xml).find("resultset");
		// var container = $("<div></div>").addClass("container");

		xmlResultsSets.each(

			function() {

				xmlResults = $(this).find("result");

				var numResults = $(this).attr("num");
				var rubriek = $(this).attr("rubriek");

				if ( numResults > 0 ) {

					xmlResults.each(

						function() {						

							var item_name = $(this).find("item_name").text();
							var item_url = $(this).find("item_url").text();

							if (rubriek == "Video") {

								var a = $("<a target=\"_blank\"></a>").attr( { href : item_url } ).html( item_name );

							} else {

								var a = $("<a></a>").attr( { href : item_url } ).html( item_name );

							}

							var dd = $("<dd></dd>").append( a );
							
							if (searchtype == "magazine") {
							
								dd.insertAfter("dt.magazine");
							
							} else if (searchtype == "agenda"){
							
								dd.insertAfter("dt.agenda");
							
							} else if (searchtype == "video"){
							
								dd.insertAfter("dt.video");
								
							} else if (searchtype == "download"){
							
								dd.insertAfter("dt.download");
							
							
							} else {
								
								dl.append( dd );
							
							}

						}

					);
					
					$(".loader_"+searchtype).fadeOut();

				}

			}

		);

	} else {

		$(".loader_" + searchtype).fadeOut();
		
		var dd = $("<dd></dd>").text( "geen resultaten gevonden" );

		/*
		if (searchtype == "magazine") {

			dd.insertAfter(".magazine");

		} else 
		*/
		
		if (searchtype == "agenda" || searchtype == "video" || searchtype == "magazine" || searchtype == "download" ) {
		
			$("dt." + searchtype).remove();
	
	/*		
		} else if (searchtype == "agenda" || searchtype == "video") {
			
			$("."+searchtype).fadeOut();
	*/
		} else {

			dl.append( dd );

		}


		if (searchtype == "magazine" || searchtype == "artiest") {			
		
			$(".loader_"+searchtype).fadeOut();
		
		}

	}

	
	
	$("#firstname").val( numReturned );
	
	if ( numReturned == numToReturn )
	{
		$("#searchresults .container").show();
		numReturned = 0;
		
		hideLoader();
	}
	
	

}

/*
	xml zoekresultaten omzetten naar dom-objecten voor search pagina
*/	
function convertSearchXML(xml) {

	var xmlResults	= $(xml).find("result");
	var numResults	= xmlResults.length;
	var trefwoord	= $(xml).find("results").attr("match");
	var searchtype	= $(xml).find("results").attr("type");
	var parent		= $("#to_"+searchtype);

	if ( numResults > 0) {

		var xmlResultsSets = $(xml).find("resultset");

		xmlResultsSets.each(

			function() {

				xmlResults = $(this).find("result");

				var numResults = $(this).attr("num");
				var rubriek = $(this).attr("rubriek");

				if ( numResults > 0 ) {

					xmlResults.each(

						function() {						

							var item_name = $(this).find("item_name").text();
							var item_url = $(this).find("item_url").text();

							if (rubriek == "Video") {

								var a = $("<a target=\"_blank\"></a>").attr( { href : item_url } ).html( item_name );

							} else {

								var a = $("<a></a>").attr( { href : item_url } ).html( item_name );

							}

							var h4		= $("<h4></h4>").append( a );
							var div		= $("<div></div>").append( h4 ); 
							var item	= $("<div class=\"item\"></div>").append( div );
							
							item.insertAfter( parent );

						}

					);
						
					$(".loader_"+searchtype).fadeOut();

				}

			}

		);

	} else {
				
		var p = $("<p></p>").text( "geen resultaten gevonden" );

		if (searchtype == "agenda" || searchtype == "video") {
		
			$(".wrap_"+searchtype).fadeOut();
			$("#to_"+searchtype).fadeOut();
					
		} else {
		
			p.insertAfter( parent );
		
		}
						
		$(".loader_"+searchtype).fadeOut();

	}

}


function replace( str, naald, rep)
{
	var test = new RegExp( naald, "i");

	return str.replace(test, rep);

}

function getResults(str, type, limit) {

	$.get(
		"http://www.muziek.nl/page/xml_search/" + str + "/" + type + "/" + limit,
		{},
		convertXML,
		"xml"
	);

}

function getSearchResults(str, type, limit) {

	$.get(
		"http://www.muziek.nl/page/xml_search/" + str + "/" + type + "/" + limit,
		{},
		convertSearchXML,
		"xml"
	);

}

/*
	searchbox
*/
var searchBoxTimer = false;
var previousKeyword = "";

function clearTimer() {

	try { window.clearTimeout( searchBoxTimer ); } catch(e) {}

}

function showLoader() {

	$("#loader").fadeIn();

}

function hideLoader() {

	$("#loader").fadeOut();

}

function initSearchBox() {		

	var def = $("#trefwoord").val();		

	$("#trefwoord").bind("focus",
		
		function() {

			if ( $(this).val() == def) {

				$(this).val("");

			}

		}

	);

	$("#trefwoord").bind("blur",
		
		function() {

			if ($(this).val() == "") {

				$(this).val(def); 

			}

		}

	);

	$("#trefwoord").bind("keyup",
	
		function(event) {

			/* escape key */
			if ( event.keyCode == 27 ) {

				clearTimer();

				hideLoader();

				$(this).val("");

				$("#searchresults").empty();

			} else {

				if ( $(this).val() != "" ) {

					showLoader();

					clearTimer();					

					searchBoxTimer = window.setTimeout( 'trySearch()', 1000 );				

				} else {

					clearTimer();		

					hideLoader();

					$("#searchresults").empty();

				}

			}

		}

	);

	$("#searchresults").empty();

	$("#searchresults").bind(

		"click",

		function(event) {

			//alert( event.target.id );

			//alert( $(event.target).is(".resultsbox") );

			if ( $(event.target).is("#searchresults, #searchresults * ") ) {

			} else {

				$("#searchresults").empty();

			}

		}

	);

	$(document.body).mousedown( checkExternalClick );

}

function checkExternalClick(event) {

	var $target = $(event.target);

	if ( $target.parents("#searchresults").length == 0 ) {

		$("#searchresults").empty();

	}

}

function initSearch(searchStr) {

	getSearchResults( searchStr, "magazine", "50" );
	getSearchResults( searchStr, "agenda", "50" );
	getSearchResults( searchStr, "video", "50" );
	getSearchResults( searchStr, "artiest", "50" );
	getSearchResults( searchStr, "download", "50" );
	getSearchResults( searchStr, "winkel", "50" );
	
	/* tijdelijk aangezien de winkel nog niet doorzocht kan worden */
	//	var p = $("<p></p>").text( "geen resultaten gevonden" );
	//	$(".loader_winkel").fadeOut();
	//	p.insertAfter("#to_winkel");
	/* tijdelijk aangezien de winkel nog niet doorzocht kan worden */

}

function trySearch()
{

	var trefwoord = $("#trefwoord").val();
	
	if ( trefwoord != "" ) {		

		$("#searchresults").empty();

		var container = $("<div></div>").addClass("container");
		var closer = $("<a></a>").addClass("closer").attr("title","sluiten").attr("href","#").html("sluiten");
		
		closer.click(

			function() {
		
				$("#searchresults").empty();
		
			}
		
		);
		
		container.append( closer );
	
	/*
	<dd class=\"loader_winkel\">Loading</dd>
	<dd class=\"loader_download\">Loading</dd>
	<dd class=\"loader_magazine\">Loading</dd>
	*/
		var html_magvid		= $("<dl id=\"magvid\"><dt class=\"magazine\">Magazine</dt><dt class=\"agenda\">Agenda</dt><dt class=\"video\">Video</dt><dt class=\"download\">Downloads</dt></dl>");
		var html_artist		= $("<dl id=\"artiest\"><dt>Artiesten</dt></dl>");
		var html_shop		= $("<dl id=\"winkel\"><dt>Winkel</dt></dl>");	
		//var html_download	= $("<dl id=\"download\"><dt>Downloads</dt></dl>");

		container.append( html_magvid );
		container.append( html_artist );
		container.append( html_shop );
		//container.append( html_download );

		$("#searchresults").append( container );
		
		// reset 
		numReturned = 0;

		getResults( trefwoord, "magazine", "6" );
		getResults( trefwoord, "agenda", "2" );
		getResults( trefwoord, "video", "2" );
		getResults( trefwoord, "artiest", "14" );
		getResults( trefwoord, "download", "14" );
		getResults( trefwoord, "winkel", "14" );
		
	/* tijdelijk aangezien de winkel nog niet doorzocht kan worden */
	//	var dd_shop = $("<dd></dd>").text( "geen resultaten gevonden" );
	//	$(".loader_winkel").fadeOut();
	//	html_shop.append( dd_shop );
	/* tijdelijk aangezien de winkel nog niet doorzocht kan worden */

		var a = $("<a></a>").attr( { href : "/page/search/" + trefwoord } ).html( "meer resultaten..." );
		var p = $("<p></p>").addClass("more-details").append( a );

		container.append( p );
		
		container.hide();

		$("#searchresults").append( container );

	}

	clearTimer();

}

/*

*/
function openWindow(pad,naam,breed,hoog)

{

	var top  = ( (screen.height/2)-(hoog/2) );

	var left = ( (screen.width/2)-(breed/2) );

	window.open(pad, naam, "width=" + breed + ",height=" + hoog +", top=" + top + "px, left=" + left + "px, toolbar=no,location=no,directories=no,status=0,resizable=no,scrollbars=no,menubar=no");

}

function initPopup() 
{
	$("a.popup").each(

		function(i)
		{
			$(this).click(
	

				function()
				{
					var poplink = $(this).attr('href');

									

					openWindow(poplink, i, 480, 420);	

					

					return false;

				}

			);

			

		}

	);

}
/*

function initPopup()

{ 

	$('a.popup').click( function() {

		window.open(this.href,this,'width=480,height=420');  

    	return false;

	});

}

*/
function initExternalLinks()
{

	var h = window.location.host.toLowerCase();
	// $("a[@href^='http']:not([@href^='http://" + h + "']):not([@href^='http://www." + h + "']), a[@href$='.pdf']").attr("target","_blank");
	var h2 = "http://shop.muziek.nl";
	var h3 = "http://new.highfidelitydiscs.nl";
	var h4 = "http://www.muziek.nl";
	
	$("a[@href^='http']:not([@href^='http://" + h + "']):not([@href^='http://www." + h + "']):not([@href^='" + h2 + "']):not([@href^='" + h3 + "']):not([@href^='" + h4 + "']), a[@href$='.pdf']").attr("target","_blank");
}


