var aDayParts = {};

$J(document).ready(function(){

	$J('.slider li').each(function(){
		console.log($J(this).width())
	})

	$J().mousemove(function(e){
		$J('.spinner').css('top',e.pageY-10).css('left',e.pageX+10);
	});

	/**
	 * BIND [ENTER] LISTENERS TO FOMRS
	 * Bind it to input fields (textareas need to be able to use [enter])
	 */
	$J('input').keypress(function(e){
		if(e.which == 13){
			$J(this).parents('form').submit();
		}
	});

	/**
	 * BIND STAR RATINGS AND LISTENERS
	 * Note that dynamicaly created lists add their own stars and listeners
	 */
	// Bind star rating to checkboxes
	// Put inside function, gets called when dynamicaly creating HTML too
	attachProgramRating('.rate-program');

	// Add click listener to PREF list rating stars
	$J('input.rate-list').rating({required:true});

	$J('div.rate-list')
		.find('.star, .cancel')
			.click(function(){

				startspinner();

				var date 	= $J(this).siblings('input').attr('name');
				var rating 	= $J(this).siblings('input').val();

				if(rating == '') rating = 0;


				// Set the database
				$J.get('/perstvgids/ajax_rateprefguide/'+date+'/'+rating+'/',function(){
					stopspinner();
				});
			});


	/**
	 * STEP 2/3
	 */
	// Toggle program rating list (register or settings)
	// Toggle channel selection list
	$J('div.step ul.programlist li div span.toggle').click(function(){

		var parentListNode = $J(this).parent().parent();

		if($J(parentListNode).attr('class') == 'selected')
		{
			$J(parentListNode).removeClass('selected');
		}
		else
		{
			$J(parentListNode).siblings('.selected').removeClass('selected');
			$J(parentListNode).addClass('selected');
		}
	});

	/**
	 * STEP 3
	 */
	// Toggle select all/none on channel selection in registration/options
	$J('.channeltoggle').click(function(){

		var childboxNodes = $J(this).parent().siblings().find('.tog');

		if(this.checked == true)
		{
			$J(childboxNodes).attr('checked','true');
		}
		else
		{
			$J(childboxNodes).removeAttr('checked');
		}
	});


	/**
	 * PERSOONLIJKE GIDS
	 */


	// 'Toon alle aanbevelingen' click listener
	$J('a.showall').click(function(){
		toggleListNumProgs('show');
	});

	$J('a.toggleView').click(function(){
		toggleListView($J(this).attr('rel'));
	})

	// Toggle PREF list rating
	$J('.rankdagdeel').click(function(){
		$J('div#bbr1').slideToggle('medium');
	});


	/**
	 * Genre selection bar
	 */
	updateGenreBar();


	/**
	 * Behaviour for mijn tvgids settings
	 */
	// add click handler for next button (used to be in html template)
	if ($J('.pg .extra_opties').length > 0)
	{
		// add form check on submit when we're on the extra options page
		$J('.pgreg .nextbutton').click(function() {
			if (checkExtraOptionsForm())
			{
				document.register.submit();
			}

			return false;
		});
	}
	else
	{
		// add regular form submit
		$J('.pg.pgreg .nextbutton').click(function(){
			document.register.submit();
			return false;
		});
	}

	// add click handler for account deletion checkbox
	$J('.pg #delete_account').click(function(){
		toggleDeleteAccountPasswordField();
	});
	// hide the password block (is shown in lightview box)
	$J('.pg .setting #passwordblock').hide();

	// show the genres/trefwoorden inputs on page load if the corresponding checkbox is checked
	if ($J('.pg #filter_genres').is(':checked') == true)
	{
		$J('.pg #genres').show();
	}
	if ($J('.pg #filter_trefwoorden').is(':checked') == true)
	{
		$J('.pg #trefwoorden').show();
	}

	// add click handlers for tv agenda genres/trefwoorden checkbox
	$J('.pg #filter_genres').click(function(){
		$J('.pg #genres').slideToggle();
	});
	$J('.pg #filter_trefwoorden').click(function(){
		$J('.pg #trefwoorden').slideToggle();

		// set focus on trefwoorden textarea if it is shown
		if ($J('.pg #trefwoorden').css('display') == 'block')
		{
			$J('.pg #trefwoorden').focus();
		}
	});

	// add change handler for trefwoorden textarea
	$J('.pg #trefwoorden').change(function() {
		checkTrefwoorden();
	});

/*
	// due to a non-cooperating IE, we can't use this handler but have to place the code inline
	// add click handlers for the delete account-lightview buttons
	$J('#lightview #confirm_delete_account').click(function() {
		document.form_delete_account.submit();
		Lightview.hide();
		return false;
	});
*/
})


/* ==========================
 * END ON LOAD
 * ======================= */

/*
 * TOP TAB CONTROL
 */
function selectTopTab(tabNode, clickedTab)
{
	var tabClasses = $J('#'+tabNode).attr('class');

	// Only load the list when not loaded yet
	if (tabClasses.indexOf('loaded') < 0) {
		switch (tabNode) {
			case 'top5block':
				var list = "top5";
				break;
			case 'blockstraks':
				var list = "straks";
				break;
			case 'blocknu':
				var list = "nu";
				break
		}

		// Load the HTML and attach the star rating
		startspinner();
		$J('#'+tabNode)
			.addClass('loaded')
			.load('/perstvgids/ajax_getshortlist/'+list+'/',function(){

				// show the content
				topTabShow(tabNode, clickedTab);

				// Attach star rating
				attachProgramRating('.rate-program');

				stopspinner();
			});
	}
	else
	{
		topTabShow(tabNode, clickedTab);
	}
}
function topTabShow(tabNode, clickedTab)
{
	// Manipulate the DOM to show selected tab and tabcontent
	$J('#top5block, #blockstraks, #blocknu').css('display', 'none').removeClass('selected');
	$J('#b_tab_top5, #b_tab_nu, #b_tab_straks').removeClass();

	$J(clickedTab).parent('li').attr('class', 'selected');
	$J('#'+tabNode).css('display', 'block');
}

/*
 * CLOUD TAB CONTROL
 */
function selectCloudTab(tabNode, clickedTab)
{
	var tabClasses = $J('#'+tabNode).attr('class');
	var dateInterval = $J('input.currInterval').val();


	// Only load the list when not loaded yet
	//if (tabClasses.indexOf('loaded') < 0) {
		switch (tabNode) {
			case 'tab_week':
				var list = "week";
				break;
			case 'tab_best':
				var list = "best";
				break;
		}
		// sitestat foor tabs
		sitestat('http://nl.sitestat.com/klo/bvpb/s?tvgids.mtvg.'+tabNode+'&amp;category=tvgids&ns_channel=tvgids&amp;ns_webdir=tvgids');

		// Load the HTML and attach the star rating
		startspinner();
		$J('#'+tabNode).addClass('loaded').load('/perstvgids/ajax_getcloud/'+list+'/'+dateInterval+'/', function(){
			// Show the content
			cloadTabShow(tabNode, clickedTab)

			stopspinner();
		});
	//}
	//else
	//{
		// Show the content
	///	cloadTabShow(tabNode, clickedTab);
	//}
}
function cloadTabShow(tabNode, clickedTab)
{
	// Manipulate the DOM to show selected tab and tabcontent
	$J('#tab_week, #tab_best').css('display', 'none');
	$J('#b_tab_week, #b_tab_best').removeClass('selected').addClass('special');

	$J(clickedTab).parent('li').addClass('selected').removeClass('special');
	$J('#'+tabNode).css('display', 'block');
}


/*
 * TOGGLE PREF PROGRAM LIST TOP PARTS (dagdeel/zender)
 *
 * Needs to be done by function in stead of jquery listener because page
 * takes a long time to fully load (ads ?)
 *
 * @param node		Object|Bool	DOM node of part to be selected, set false to select all
 */
function toggleList(node, actionAll)
{
	// Get some params
	var classNames 		= $J(node).children('ul.programlist').attr('class');
	var parentTabId 	= $J(node).parent().parent().attr('id');

	// Close opened lists, only if selection is shown
	/*if ($J('a.showall').length > 0) {
		$J('#' + parentTabId + ' ul.opened').parent('li').removeClass('selected');
		$J('#' + parentTabId + ' ul.opened').removeClass('opened').css('display', 'none');
	}*/

	if (classNames == undefined)
	{
		classNames = '';
	}

	// Only for lists that aren't opened allready
	if (classNames.indexOf('opened') < 0)
	{
		$J(node).find('li').removeAttr('style');
		$J(node).children('ul.programlist').addClass('opened').css('display','block');
		$J(node).addClass('selected');
	}
	else
	{
		$J(node).children('ul.programlist').removeClass('opened').css('display','none');
		$J(node).find('li').removeClass('selected');
		$J(node).removeClass('selected');
	}
}

/**
 * Open or close the whole list
 */
var toggleView;

function toggleListAll()
{
	if (toggleView == 'show')
	{
		// Close the whole list
		$J('ul.programlist li').css('display','none');
		$J('li.proglist').children('ul.programlist').removeClass('opened').css('display','none');
		$J('li.proglist').removeClass('selected');

		// Open the previous selected part
		toggleList($J('li.currSelected'))

		// remove the currSelected class
		$J('ul.parttime li.currSelected').removeClass('currSelected');
		toggleView = 'hide';

		// Hide non-userdayparts (selected in instellingen 4.)
		$J('li.hidepart').hide();
	}
	else
	{
		// Set current selected part, we can use this later to close all except the current selected part
		$J('ul.parttime li.selected').addClass('currSelected');
		toggleView = 'show';

		// Open the whole list
		$J('ul.programlist li').removeAttr('style');
		$J('li.proglist').children('ul.programlist').addClass('opened').css('display','block');
		$J('li.proglist').addClass('selected');

		// Show non-userdayparts (selected in instellingen 4.)
		$J('li.hidepart').show();
	}

}

/*
 * TOGGLE PREF LIST PROGRAM DETAIL
 */
function toggleProgram(node)
{
	// Get params
	nodeClass = $J(node).attr('class');

	if (nodeClass.indexOf('selected') >= 0)
	{
		$J(node).removeClass('selected');

		$J(node).children('.full').addClass('hidden');
		$J(node).children('.trunc').removeClass('hidden');
	}
	else
	{
		$J(node).parent().children('li.selected').removeClass('selected');
		$J(node).addClass('selected');

		$J(node).children('.trunc').addClass('hidden');
		$J(node).children('.full').removeClass('hidden');
	}
}


/**
 * Toggles beween 'toon alle aanbevelingen' and 'toon selectie'
 */
function toggleListNumProgs(how)
{
	setDayParts(how);

	switch (how)
	{
		case 'show':
			var aCurrClass  = 'showall';
			var aNewClass   = 'hideall'
			var buttonText  = 'Toon selectie';
			var liCurrClass = 'hidden';
			var liNewClass  = 'unhidden';
			var newAction   = 'hide';
			break;
		case 'hide':
			var aCurrClass  = 'hideall';
			var aNewClass   = 'showall'
			var buttonText  = 'Toon alle aanbevelingen';
			var liCurrClass = 'unhidden';
			var liNewClass  = 'hidden';
			var newAction   = 'show';
			break;
	}

	$J('a.' + aCurrClass).unbind('click');

	$J('a.' + aCurrClass + ' span').html(buttonText);
	$J('li.' + liCurrClass).removeClass(liCurrClass).addClass(liNewClass);

	$J('a.' + aCurrClass).removeClass(aCurrClass).addClass(aNewClass);

	// show the new lists with the remembered list expanded
	toggleList($J('li.currSelected'))
	toggleListAll();

	$J('a.' + aNewClass).click(function(){
		toggleListNumProgs(newAction);
	});
}

/*
 * Toggles between 'dagdeel' and 'zender' view of recommendations.
 * Actually uses the 'old' tabcontent to store the zender view in.
 */
function toggleListView(view)
{
	// Get / set some params
	var currInterval 		= $J('input.currInterval').val();

	switch (view)
	{
		case 'zender':
			var toTabContent	= "tab_zender";
			var newButtonText 	= "Per dagdeel";
			var newView			= "dagdeel";
			break;
		case 'dagdeel':
			var toTabContent	= "tab_dagdeel";
			var newButtonText 	= "Per zender";
			var newView			= "zender";
			break;
	}

	// Switch the content by pretending to click (the old) 'Zender' tab
	// Before the tab 'Aanbevolen' got implemented, to tabs 'Zender' and 'Dagdeel' existed.
	// The 'dagdeel' tab changed to 'Aanbevolen', the 'Zender' tab got removed, but we still use it's tab content.
	//selectProgTab(toTabContent, false, currInterval, view);

	// Change the buttontext and click event
	$J('a.toggleView').unbind('click');

	$J('a.toggleView span').html(newButtonText);

	$J('a.toggleView').click(function(){
		toggleListView(newView);
	});
}

/*
 * Unhides the channel parts that have programs inthem that need to be shown (that are the same as the programs in 'dagdeel' view
 */
function unhideList()
{
	$J('li.proglist').each(function(){
		if ($J(this).find('li.nothidden').length > 0)
		{
			$J(this).removeClass('hidden');
		}
	});
}

function attachProgramRating(className)
{
	// Attach rating stars
	$J('input'+className).rating({required:true});
	$J('.rating').css('display','inline');
	// Add click listener
	// Ratings that allready have a click listener have to omitted, else they'll get mulitple click listeners
	// Unbinding is not an option, it messes with the rating stars internal clicks
	var attachedClassName = className.replace('.','')+' attached';

	$J('div'+className+'[class!="'+attachedClassName+'"]')
		.addClass('attached')
		.find('.star, .cancel')
			.click(function(){
				var id 		= $J(this).siblings('input').attr('name');
				var rating 	= $J(this).siblings('input').val();

				if(rating == '') rating = 1;

				// Set the database
				rateProgram(id, rating)
			});
}

function rateProgram(id, rating)
{
	startspinner();

	if(rating == '') rating = 1;

	// sometimes the id can be sepperated by a #-, where # can be any text
	id += '';	// convert id to a string, to be able to use indexOf()
	if(id.indexOf('-') >= 0)
	{
		var splt = id.split("-");
		var id = splt[1];
	}

	// Set the database
	$J.get('/perstvgids/ajax_rateprogram/'+id+'/'+rating+'/',function(){
		stopspinner();
	});
}

/**
 * Remove a program from the list and tag cloud, give it a rating 1
 */
function delProgram(id, title, genre, event, isSerie)
{
	selectedTab = $J('ul.tabs4 li.selected, ul.tabs4 li.selectedfirst').attr('id');

	// Set the database
	listId = $J('.rate-list').children('input').attr('name');

	switch (selectedTab)
	{
		case 'b_tab_zender':
		case 'b_tab_dagdeel':
			msg = "Hiermee verwijder je deze aanbeveling uit Mijn TVGids.nl.";
			break;

		case 'b_tab_genre': // Is actually agenda tab
		default:
			var oCursor = getCursorPosition(event);

			var aAnswers = [];

			if (isSerie == 1)
			{
				aAnswers[0] = 'Serie|removeAgendaItem(\'' + id + '\', \'' + title + '\', \'' + genre + '\', \'' + listId + '\', \'' + selectedTab + '\', 1)';
				aAnswers[1] = 'Uitzending|removeAgendaItem(\'' + id + '\', \'' + title + '\', \'' + genre + '\', \'' + listId + '\', \'' + selectedTab + '\', 0)';
				aAnswers[2] = 'Annuleren|/*no action*/';
				var givenAnswer = showQuestion('Hiermee verwijder je dit programma uit je TV Agenda. Wil je de hele serie of alleen deze uitzending verwijderen?', aAnswers, oCursor.x, oCursor.y, 'left', id);
			}
			else
			{
				aAnswers[0] = 'Verwijderen|removeAgendaItem(\'' + id + '\', \'' + title + '\', \'' + genre + '\', \'' + listId + '\', \'' + selectedTab + '\', 0)';
				aAnswers[1] = 'Annuleren|/*no action*/';
				var givenAnswer = showQuestion('Hiermee verwijder je dit programma uit je TV Agenda. Wil je doorgaan?', aAnswers, oCursor.x, oCursor.y, 'left', id);
			}

			// stop processing
			return true;
	}

	if (!confirm(msg))
	{
		return false;
	}

	startspinner();

	removeProgramHtml(genre, id);

	// Rate the program
	rateProgram(id, 1);

	/**
	 * Removed programs get a 1 rating and will be filtered from the list on this rating
	 * (only > 1 will be shown)
	 */
	$J.get('/perstvgids/ajax_delprogram/' + id + '/' + listId + '/' + selectedTab + '/' + title + '/', function(){
		stopspinner();
	});
}

function removeAgendaItem(id, title, genre, listId, selectedTab, removeSerie)
{
	$J.get('/perstvgids/ajax_delprogram/' + id + '/' + listId + '/' + selectedTab + '/' + title + '/' + removeSerie + '/', function(){
	});

	// remove the html nodes for this program
	removeProgramHtml(genre, id);

	// Rate the program
	rateProgram(id, 1);
}

function removeProgramHtml(genre, id)
{
	// get the correct html node
	node = '.programlist li.' + id + ' .listing';

	// Remove program from list
	$J(node).parent().fadeOut('slow', function(){
		$J(this).remove();

		// Remove genre selection if no programs with same genre exist
		if ($J('div.tabcontent li.genre-'+genre.toLowerCase()).length <= 0)
		{
			$J('ul.sc_menu a.'+genre.toLowerCase()).parent().remove();

			// Remove this genre selection block, the spacer item always remains
			if ($J('ul.sc_menu li').length == 1)
			{
				$J('div.genreblock').parent().fadeOut('slow');
			}
		}
	});

	// Remove program from cloud
	$J('div.cloud a.'+id).fadeOut('slow', function(){
		$J(this).remove();
	});

	// Remove dagdeel or zender if no more items are present
	iRemainingItems = $J(node).parent().siblings("li[class!='removed']").length;
	if (iRemainingItems == 0) {
		$J(node).parents('.proglist').fadeOut();
	}
}

function displayHtmlMessage(message)
{
	// remove any existing message
	removeHtmlMessage();

	var html = '<div class="pg pgmsg"><h1 class="world"><span>Informatie</span></h1><div class="processtabs"><p><strong>' + message + '</strong></p><br class="clearer" /></div></div>';

	// display the message
	$J('#col-one-pg-wide').prepend(html);
}

function removeHtmlMessage()
{
	$J('#col-one-pg-wide .pgmsg').remove();
}

/*
 * Delete a users agenda
 */
function delAgenda()
{
	if ($J('#tab_genre ul li').length > 0)
	{
		if (confirm('Weet je zeker dat je alles uit je TV Agenda wilt verwijderen?'))
		{
			$J.get('/perstvgids/ajax_delagenda/', function(resp)
			{
				if (resp == 'true')
				{
					$J('.genreblock').parent().fadeOut('medium');
					$J('#tab_genre ul').css('min-height', '41px').children().fadeOut('medium', function()
					{
						$J('#tab_genre ul').html('<div class="noresult">Er zijn geen programma\'s om weer te geven.</div>');
					});
				}
				else
				{
					alert('Je TVAgenda kon niet worden leeg gemaakt.');
				}
			});
		}
		else
		{
			return false;
		}
	}
}

/**
 * Shortlist (TOP5 e.d.) list toggle
 */
function toggleShortlist(node)
{
	startspinner();

	var parentNode = $J(node).parent();
	var currClass = $J(parentNode).attr('class');

	if(currClass.indexOf('selected') >= 0)
	{
		$J(parentNode).removeClass('selected');
	}
	else
	{
		$J(parentNode).siblings('.selected').removeClass('selected');
		$J(parentNode).addClass('selected');
	}

	stopspinner();
}

/**
 * Show and hide list rating button
 * Note that there is a smarty templating script added to inc_perstvgids2_program.html too
 */
function showRateList(bool)
{
	switch(bool)
	{
		case true:
			$J('.ratelist').show();
		break;
		case false:
			$J('.ratelist').hide();
		break;
	}
}

function showViewSelect(bool)
{
	switch(bool)
	{
		case true:
			$J('.toggleView').show();
		break;
		case false:
			$J('.toggleView').hide();
		break;
	}
}

/*
 * Start/stop loading spinner
 */
function startspinner()
{
	$J('.spinner').css('display','inline');
}
function stopspinner()
{
	$J('.spinner').css('display','none');
}

/**
 * HIGHLIGHTS FORM FIELDS AFTER VALIDATION
 *
 * @param sFieldNames comma seppearated list of fieldnames
 */
function pgHighlightFields(sFieldNames)
{
	var aFields = sFieldNames.split(',');

	for (var i = 0; i < aFields.length; i++)
	{
		// Get the input field id, to select the label (for='')
		var sFieldId = $J("input[name='" + aFields[i] + "']").attr('id');

		// If the field id can't be found with with the field name,
		// just use the fieldname as id
		if (sFieldId == undefined)
		{
			sFieldId = aFields[i];
		}

		// Highlight the fields
		// Add a key up listener
		$J("label[for='" + sFieldId + "'], input[name='" + aFields[i] + "'], span." + aFields[i])
			.addClass('highlight')
			.keyup(function(sFieldId){
				$J(this).removeClass('highlight');
				// We have to get the id again, sFieldId will not work
				var tmpId = $J(this).attr('id');
				$J("label[for='" + tmpId + "']").removeClass('highlight');
			});
	}
}

/**
 * Selecteer ale programma's in het gekozen genre bij 'Alle zenders'
 */
function highlightGenre(oClickedNode, sGenre)
{
	if (sGenre != '' || typeof(sGenre) !== undefined)
	{
		sClassNames = $J(oClickedNode).attr('class');

		$J('ul.programlist li.genre, ul.sc_menu a').removeClass("active");

		if (sClassNames.indexOf('active') == -1)
		{
			$J('ul.programlist li.genre-' + sGenre + ', ul.sc_menu a.' + sGenre).addClass("active");
		}
	}
	return false;
}

/**
 * Shows or hides parts of the day
 */
function setDayParts(how)
{
	for (var i in aDayParts)
	{
		var sShowHideClass = '.'+initialCap(String(i));
		if (aDayParts[i] == 0 && how == 'hide')
		{
			$J(sShowHideClass).hide();
		}
		else
		{
			$J(sShowHideClass).show();
		}
	}
}

/**
 * Scroll horizontaal door de genres bij 'alle zenders'
 *
function scrollGenres(iDirection)
{
	var iScrollLen 	= 380;

	var iLeft 		= parseInt($J('div#selectie-genres div#genres').css('left'));
	var iCurrWidth 	= $J('div#selectie-genres div#genres').width();
	var iCurrpos	= $J('div#selectie-genres div#genres').position();

	var iRightSide = iCurrpos.left + iCurrWidth;

	console.log(iCurrpos.left);

	if (iDirection < 0)
	{
		iLeftNew = parseInt(iLeft)-iScrollLen;
		$J('div#selectie-genres div#genres').width(iCurrWidth+iScrollLen)
	}
	else
	{
		iLeftNew = parseInt(iLeft)+iScrollLen;
		$J('div#selectie-genres div#genres').width(iCurrWidth-iScrollLen)
	}

	if (iLeftNew > 0)
	{
		iLeftNew = 0;
	}

	$J('div#selectie-genres div#genres').animate({left:iLeftNew},"fast");
}
*/

/**
 * First character to Uppercase
 */
function initialCap(value)
{
	value = value.substr(0, 1).toUpperCase() + value.substr(1);
	return value;
}

/**
 * Toggle the password field for account deletion
 */
function toggleDeleteAccountPasswordField()
{
	var element = $J('.pg .setting #passwordblock');

	// remove any autocompleted value, forcing the user to _type_ the password
	var passwordfield = $J('.pg #passwordfield').val();
	$J('.pg #' + passwordfield).val('');

/*
	element.slideToggle();

	if (element.css('display') == 'block')
	{
		$J('.pg #' + passwordfield).focus();
	}
*/
}

function checkTrefwoorden()
{
	var element = $J('.pg #trefwoorden');

	if ($J.trim(element.val()) == '')
	{
		return false;
	}

	trefwoorden = element.val().split(',');

	$J.each(trefwoorden, function(i, val) {
		if ($J.trim(val).length > 0 && $J.trim(val).length < 3)
		{
			var message = 'Het trefwoord "' + $J.trim(val) + '" is te kort en zal niet worden gebruikt.' + "\n" + 'De minimum lengte van een trefwoord is 3 letters.';
			displayHtmlMessage(message);
			return false;
		}
		else
		{
			// remove any existing message
			removeHtmlMessage();
		}
	});

	return true;
}

function checkExtraOptionsForm()
{
	// handle account deletion
	if ($J('.pg #delete_account').is(':checked'))
	{
		Lightview.show({
			href: '#form_delete_account',
			rel: 'inline',
			caption: 'Mijn TVGids account verwijderen',
			options: {
				width: 350,
				height: 150,
				onOpen : function()
				{
					$J('#simplemodal-data #delete_account').hide();
					$J('#simplemodal-data #lbl_delete_account').hide();

					$J('#simplemodal-data #passwordblock').show();
				},
				onClose : function()
				{
					$J('.pg .setting #delete_account').show();
					$J('.pg .setting #lbl_delete_account').show();

					$J('.pg .setting #passwordblock').hide();
				}
			}
		});

		return false;
	}

	// only check genres if the filter itself is checked
	if ($J('.pg #filter_genres').is(':checked'))
	{
		var genres = $J('.pg #genres input:checked');

		if (genres.length == 0)
		{
			var message = 'Selecteer tenminste 1 genre uit de lijst';
			displayHtmlMessage(message);
			return false;
		}
	}

	return true;
}

function toggleAgendaDayPart(iDag, iDagdeel, target)
{
	
	if ($J(target).hasClass("empty"))
	{
		startspinner();

		$J.get('/perstvgids/ajax_getagendabydayslot/dagdeel/'+iDag+'/'+iDagdeel+'/', function(data)
		{
			$J(target).removeClass("empty");
			$J(".programlist",target).html(data);

			attachProgramRating('.rate-program');
			
			var aGenres = new Array();

			$J('.extra_genres li', target).each(function()
			{				
				var sGenrename = $J('a', this).attr('class');

				if ($J('.sc_menu li a.'+sGenrename).size() == 0)
				{
					$J('ul.sc_menu').append( $J(this) );
				}
			});

			$J('.tooltip_mtvg', target).tooltip({
				track: true,
				showURL: false,
				delay: 1000,
				fade: 0, // delay gives problems with a fade > 0
				extraClass: 'mtvg_tooltip'
			});

			updateGenreBar();
			toggleList(target);		
			stopspinner();
		}, "html");
	}
	else 
	{
		toggleList(target);
	}
	
}

function updateGenreBar()
{
	
		if ($J('div.sc_menu').length > 0)
		{
		/* Get our elements for faster access and set overlay width */
		var div = $J('div.sc_menu');
		var ul = $J('ul.sc_menu');
		// unordered list's left margin
		var ulPadding = 15;

		//Get menu width
		var divWidth = div.width();

		//Remove scrollbars
		div.css('overflow','hidden');

		//Find last image container
		var lastLi = ul.find('li:last-child');
		
		// unbind old mousemove event
		div.unbind('mousemove');

		//When user move mouse over menu
		div.mousemove(function(e){
			// recalc, items can be removed
			var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
			var left = (e.pageX - div.offset().left) * (ulWidth - divWidth) / divWidth;
			div.scrollLeft(left);
		});
	}
}

