$J(document).ready(function(){

	$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');
	});

})


/* ==========================
 * END ON LOAD
 * ======================= */


/*
 * PREF TAB CONTROL
 *//*
function selectProgTab(tabNode, clickedTab, interval)
{
	// Get params
	var tabClasses = $J('#'+tabNode).attr('class');

	// Only load the list when not loaded yet or a new view is requested
	if (tabClasses.indexOf('loaded') < 0) {

		startspinner();

		switch (tabNode) {
			case 'tab_zender':
			case 'tab_dagdeel':

				switch (tabNode)
				{
					case 'tab_zender':
						var url = '/perstvgids/ajax_getpref/zender/'+interval+'/?show=zender';
						var tabContent = 'tab_zender';
						break;
					case 'tab_dagdeel':
						var url = '/perstvgids/ajax_getpref/dagdeel/'+interval+'/?show=dagdeel';
						var tabContent = 'tab_dagdeel';
						break;
				}

				$J('#'+tabNode).addClass('loaded').load(url, function(){
					// Show the content
					progTabShow(tabContent, clickedTab);
					attachProgramRating('.rate-program');
					stopspinner();
				});
				break;
			case 'tab_genre':
				$J('#'+tabNode).addClass('loaded').load('/perstvgids/ajax_getagenda/dagdeel/'+interval+'/?show=agenda', function(){
					// Show the content
					progTabShow(tabNode, clickedTab);
					attachProgramRating('.rate-program');
					stopspinner();
				});
				break
			case 'tab_special':
				$J('#'+tabNode).addClass('loaded').load('/perstvgids/ajax_geteditortips/dagdeel/'+interval+'/?show=redactietips', function(){
					// Show the content
					progTabShow(tabNode, clickedTab);
					attachProgramRating('.rate-program');
					showRateList(false);
					$J('a.showall').click();
					stopspinner();
				});
				break
		}



	}
	else
	{
		switch (tabNode)
		{
			case 'tab_zender':
			case 'tab_dagdeel':

				switch (tabNode)
				{
					case 'tab_zender':
						var tabContent = 'tab_zender';
						var view = "zender";
						break;
					case 'tab_dagdeel':
						var tabContent = 'tab_dagdeel';
						var view = "dagdeel";
						break;
				}

				// Set a session var
				$J.get('/perstvgids/ajax_session/?show='+view);
				break;

			case 'tab_genre':
				var tabContent = tabNode;
				// Set a session var
				$J.get('/perstvgids/ajax_session/?show=agenda');
				break;
			case 'tab_special':
				var tabContent = tabNode;
				// Set a session var
				$J.get('/perstvgids/ajax_session/?show=redactietips');
				break;
		}

		// Show the content
		progTabShow(tabContent, clickedTab);


	}



	// Hide or show the rate this list button
	// Note that there is a smarty templating script added to inc_perstvgids2_program.html too
	switch (tabNode) {
		case 'tab_zender':
		case 'tab_dagdeel':
			showRateList(true);
			showViewSelect(true);
			break;
		case 'tab_genre':
		case 'tab_special':
			showRateList(false);
			showViewSelect(false);
			break
	}

}
function progTabShow(tabNode, clickedTab)
{
	// Manipulate the DOM to show selected tab and tabcontent
	$J('#tab_zender, #tab_dagdeel, #tab_genre, #tab_special').removeClass('tabcontent_selected');

	if (clickedTab !== false)	// Can be false when switch view button is clicked
	{
		$J('#b_tab_zender').attr('class', 'first');
		$J('#b_tab_dagdeel, #b_tab_genre').removeClass();
		$J('#b_tab_special').attr('class', 'special');
	}

	$J(clickedTab).attr('class', 'selected');
	$J('#'+tabNode).addClass('tabcontent_selected');

	// If view by dagdeel or zender is selected we have to remember which tabcontent is currently selected for later reference
	if (tabNode == 'tab_zender' || tabNode == 'tab_dagdeel')
	{
		$J('.tabcontent').removeClass('current');
		$J('#'+tabNode).addClass('current');
	}

	if (tabNode == 'tab_zender')
	{
		unhideList();
	}
}*/

/*
 * 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;
		}

		// 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
	$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');
	}
}

/**
 * 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';
	}
	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');
	}
}

/*
 * 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)
{
	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(node, id)
{
	selectedTab 	= $J('ul.tabs4 li.selected, ul.tabs4 li.selectedfirst').attr('id');
	
	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:
			msg = "Hiermee verwijder je dit programma uit je TV Agenda.";
	}

	if(confirm(msg))
	{
		startspinner();

		// Remove program from list
		$J(node).parent().fadeOut('slow', function(){
			$(this).remove();
		});

		// Remove program from cloud
		$J('div.cloud a.'+id).fadeOut('slow', function(){
			$(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();
		}

		// Rate the program
		rateProgram(id, 1);

		// Set the database
		listId 		= $J('.rate-list').children('input').attr('name');

		/*
		 * Removed programs get a 1 rating and will be filtered from the list on this rating (only > 1 will be shown)
		 * only agenda programs have to be deleted (by title actually)
		 */
		//if (selectedTab == 'b_tab_genre')
	//	{
			$J.get('/perstvgids/ajax_delprogram/' + id + '/' + listId + '/' + selectedTab + '/', function(){
				stopspinner();
			});
		//}

	}
	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');
			});
	}
}






