// Javascript code for the timeline plugin using jQuery.

// Moves the selection highlight to the location of the button pressed.
function buttonClicked(event, index)
{
	// Get the position of the div containing the img.
	var link = $('.wbtl-horiz-list li').eq(index).children('a');
	
	if (link != null && !link.hasClass("button-selected"))
	{
		// This will "unselect" any other buttons that were clicked before.
		$('.wbtl-horiz-list li a').removeClass("button-selected");
		
		// Now highlight the button that was clicked.
		link.addClass("button-selected");	
	}

	//return false;
}

// Calls all the init code for the timeline to be initialized.
// This is called on document ready and when a new timeline is 
// loading via ajax.
function initTimeline()
{
	// initialize scrollable
	$('.scrollable').scrollable({onBeforeSeek:buttonClicked}).navigator();
	
	// Highlight the first button.
	$('.wbtl-horiz-list li:first-child a').addClass("button-selected");
	
	// Make sure no buttons think they are selected on load.
	//$('img[class=wbtl-image]').data('isSelected', false);
	
	// Ensure the first button knows it's active.
	$('.wbtl-horiz-list li:first').addClass('active');
	
	// Initialize the tooltips for the buttons.
	//$('img[class=wbtl-image]').tooltip({
	$('#wbtl-horizontal-bar .wbtl-horiz-list li a div').tooltip({
		effect: 'fade',
		position: 'top center',
		offset: [20,0]
	});
	
	// Make sure tinymce is loaded on startup for admin modes.
	$('textarea.tinymce').trigger('loadTinyMCE');
	
	$('#wbtl-horizontal-bar').css(
		{
			'overflow' : 'hidden' // change to hidden for JS users
		});
	/*
	var config = 
	{
		width : 800,
		height: 500,
		filebrowserImageUploadUrl: '/uploader/upload.php?type=Images'
	};
	*/ 
	// Initialize the editor.
	// Callback function can be passed and executed after full instance creation.
	//$('.jquery_ckeditor').ckeditor(function() { /* callback code */ }, config);
	
	
	// Hide all the saving text.
	$('.saving-text').hide();

	// Allows for linking directly to a button on the timeline.
	if (location.hash)
	{
		var button = $('#wbtl-horizontal-bar').find('a[href='+location.hash+']');
		if (button)
		{
			button.click();
		}

		// Make sure that the page doesn't scroll to the clicked button.
		$('html, body').scrollTop(0);
	}
}




//Saves the updated button info and refreshes the whole bar.
function saveButtonInfo(saveButton)
{
	var fieldSet = saveButton.parent().parent();
	
	var timelineId = $('#wbtl-admin-select').val();
	var buttonId = fieldSet.find('input[name=button-id]').val();
	var buttonOrder = fieldSet.find('input[name=button-order]').val();
	var buttonName = fieldSet.find('input[name=button-name]').val();
	var buttonUrl = fieldSet.find('input[name=button-url]').val();
	var buttonTooltip = fieldSet.find('input[name=button-tooltip]').val();
	var buttonContent = fieldSet.find('textarea[name=button-content]').html();
	
	// The database id is stored in the value field.
	var data = 
	{
		action: 'wbtl_update_button',
		id: timelineId,
		b_id: buttonId,
		b_order: buttonOrder,
		b_name: buttonName,
		b_url: buttonUrl,
		b_tooltip: buttonTooltip,
		b_content: buttonContent
	};

	// Disable the button while saving.
	saveButton.attr('disabled', 'disabled');
	
	var savingText = fieldSet.find('.saving-text');
	savingText.show();

	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) 
	{
		// Enable the button again.
		saveButton.removeAttr("disabled");

		savingText.html('Saved');
		savingText.fadeOut(1000, function()
		{
			savingText.html('Saving...');
		});
		
		// If the image thumbnail has changed we want to reflect it live without
		// having to refresh the page.
		var urlInput = fieldSet.find('input[name=button-url]');
		if (urlInput.hasClass('dirty'))
		{
		    urlInput.removeClass('dirty');
		    
		    // Find the id of the image on the timeline strip that matches 
		    // the button id.
		    $('#image-' + buttonId).attr("src", buttonUrl);
		}
		
		// If the order has changed we want to reflect it live without
		// having to refresh the page.
		var orderInput = fieldSet.find('input[name=button-order]');
		if (orderInput.hasClass('dirty'))
		{
		    orderInput.removeClass('dirty');
		    changeTimeline(timelineId);
		}
	});
}



// Adjust the bar width if a button is added or removed.
function adjustBarWidth()
{
	var numChildren = $('#wbtl-horizontal-bar .wbtl-horiz-list').children().length;
	var newWidth = numChildren * 164;
	$('#wbtl-horizontal-bar .wbtl-horiz-list').css('width', newWidth + 'px');	
}



//Adds a button to the bottom row. Sends a request to add a new button to the db.
//PHP then will return the code for the new bar with the new button in it.
function addBottomButton(parentId)
{
	var timelineId = $('#wbtl-admin-select').val();
	
	// The database id is stored in the value field.
	var data = 
	{
		action: 'wbtl_add_bottom_button',
		id: timelineId,
		parentid: parentId
	};

	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) 
	{
		// The returned code is the code for the new button to be added 
		// and the content separated by a ','. Split it and add it to the 
		// bottom bar and the content area.
		var codeArray = response.split(',');

		// Add the new button to the bar.
		$('#wbtl-horizontal-bar .wbtl-horiz-list').append(codeArray[0]);

		// Add the content to the main area.
		$('#wbtl-content-onebar .scrollable .items').append(codeArray[1]);

		// get handle to scrollable API
		//var api = $(".scrollable").data("scrollable");
		//var newDiv = $(codeArray[1]);
		//api.addItem(newDiv);
		
		// Adjust the width to accomidate the new button.
		adjustBarWidth();
		
		// Copy the events from the first button so that we can handle clicks and tooltips
		//var firstButton = $('#wbtl-horizontal-bar .wbtl-horiz-list li:first-child');
		//var newButton = $('#wbtl-horizontal-bar .wbtl-horiz-list li:last-child');
		//newButton.copyEvents(firstButton);
		$(".scrollable").data("scrollable").addItem();
		
		// initialize scrollable
		//$('.scrollable').scrollable({onBeforeSeek:buttonClicked}).navigator();
		
		// Hide all the tables around the images to indicate mouse hovering.
		$('table[class=wbtl-image-table-show]').hide();
		
		// Make sure no buttons think they are selected on load.
		//$('img[class=wbtl-image]').data('isSelected', false);
		
		// Ensure the first button knows it's active.
		//$('.wbtl-horiz-list li:first').addClass('active');
		
		// Initialize the tooltips for the buttons.
		$('img[class=wbtl-image]').tooltip({effect: 'slide'});
		
		// Make sure tinymce is loaded on startup for admin modes.
		var newButton = $('.scrollable .items div:last-child');
		var textArea = newButton.find('.tinymce');
		textArea.trigger('loadTinyMCE');
		
		
		//$('#wbtl-horizontal-bar').css({'overflow' : 'hidden'});
		/*
		var config = 
		{
			width : 800,
			height: 500,
			filebrowserImageUploadUrl: '/uploader/upload.php?type=Images'
		};
		*/ 
		// Initialize the editor.
		// Callback function can be passed and executed after full instance creation.
		//$('.jquery_ckeditor').ckeditor(function() { /* callback code */ }, config);
		
		
		// Hide all the saving text.
		$('.saving-text').hide();
		
	});	
}


//Removes a button from the database and then refreshes the timeline to show the results.
function removeButton(removeBtn)
{
	if (!confirm("Are you sure you wish to delete the button? This cannot be undone!"))
	{
		return;
	}

	var fieldSet = removeBtn.parent().parent();
	
	var timelineId = $('#wbtl-admin-select').val();
	var buttonId = fieldSet.find('input[name=button-id]').val();

	var data = 
	{
		action: 'wbtl_remove_bottom_button',
		id: timelineId,
		b_id: buttonId
	};

	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) 
	{
		// get handle to scrollable API and add nothing. That way the list will reload.
		//var api = $('.scrollable').data('scrollable');
		//api.end();

		// Remove the content and the button from the DOM.
		$('#button-' + buttonId).remove();
		$('#content-' + buttonId).remove();
		
		// Adjust since a button is now gone.
		adjustBarWidth();
		
		//delete ($('.scrollable'));
		//$('.scrollable').scrollable().navigator();
		
		// Want to avoid this for sure if we can.
		//location.reload();

		// get handle to scrollable API and add nothing. That way the list will reload.
		//var api = $('.scrollable').data('scrollable');
		//api.reload();
		/*
		$('.scrollable').scrollable().navigator(
		{
			indexed:true
		});
		*/
		/*
		// Select the first button.
		var firstButton = $('div.wbtl-tooltip-container:first');
		alert("nodetype=" + firstButton.nodeType + " id=" + firstButton.id);
		if (firstButton.nodeType != undefined)
		{
			getMainContent($('#wbtl-admin-select').val(), firstButton);
		}
		*/
	});	

}



//Updates the select box with the timeline names from the database.
//And loads the new timeline.
function changeTimeline(timelineId)
{
	// Break this down into getting the settings and the timeline.

	///////////////////////////////////////////////////////////////////////////
	// First we'll refresh the settings area.
	///////////////////////////////////////////////////////////////////////////

	var data = 
	{
		action: 'wbtl_get_settings',
		id: timelineId
	};

	setLoadingImage($('#wbtl-edit'));
	
	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) 
	{
		$('#wbtl-edit').html(response);
	});
	
	///////////////////////////////////////////////////////////////////////////
	// Second we'll refresh the timeline itself with the new one.
	///////////////////////////////////////////////////////////////////////////

	data = 
	{
		action: 'wbtl_get_html_timeline',
		id: timelineId
	};

	setLoadingImage($('#wbtl-timeline-wrapper'));
	
	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) 
	{
		$('#wbtl-timeline-wrapper').html(response);
		$('#wbtl-horizontal-bar')
			.css(
			{
				'overflow' : 'hidden' // change to hidden for JS users
			});	

		// initialize the new timeline
		initTimeline();

	});
	
}

//Saves the timeline settings to the database and updates the listbox
//with the data returned from PHP since the name might have changed.
function saveSettings()
{
	var selectBoxIndex = $('#wbtl-admin-select').attr('selectedIndex');
	var timelineId = $('#wbtl-admin-select').val();
	var timelineType = $('input[name=numbars]:checked').val();
	var timelineName = $('input[name=tlname]').val();
	
	// The database id is stored in the value field.
	var data = 
	{
		action: 'wbtl_update_timeline',
		id: timelineId,
		type: timelineType,
		name: timelineName
	};

	// Disable the button while saving.
	$('wbtl-admin-save').attr('disabled', 'true');
	
	var savingText = $('#wbtl-admin-savearea').find('.saving-text');
	savingText.show();

	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) 
	{
		$('#wbtl-admin-select').html(response);
		
		// Now select the most recently added timeline.
		$('#wbtl-admin-select').attr('selectedIndex', selectBoxIndex);
		
		// Enable the button again.
		$('wbtl-admin-save').attr('disabled', 'false');
		
		// Show the saved sucessfully message then hide it nicely.
		savingText.html('Saved');
		savingText.fadeOut(1000, function()
		{
			savingText.html('Saving...');
		});
	});

}

//Adds a new timeline to the database. The PHP script will add a new one to the database
//then return the code for the list box with the updated options.
//Once the listbox is updated we want to select the newly added timeline.
function addNewTimeline()
{
	var data = 
	{
		action: 'wbtl_add_timeline'
	};

	// Set loading for all admin areas.
	setLoadingImage($('#wbtl-admin-select'));
	setLoadingImage($('#wbtl-edit'));
	
	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) 
	{
		$('#wbtl-admin-select').html(response);
		
		// Now select the most recently added timeline.
		var lastOption = $('#wbtl-admin-select option').length - 1;
		$('#wbtl-admin-select')[0].selectedIndex = lastOption;
		
		// For some reason the above doesn't call the onChange function
		// of the select box. So just call it on our own.
		changeTimeline($('#wbtl-admin-select').val());
	});

}

//Removes the currently selected timeline from the database.
function removeTimeline(timelineId)
{
	// TODO: make sure we can't remove if there are no timelines.
	
	
	
	// The database id is stored in the value field.
	var data = 
	{
		action: 'wbtl_remove_timeline',
		id: timelineId
	};

	// Set loading for all admin areas.
	setLoadingImage($('#wbtl-admin-select'));
	setLoadingImage($('#wbtl-edit'));
	
	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) 
	{
		$('#wbtl-admin-select').html(response);
		
		// Now select the the first option.
		$('#wbtl-admin-select')[0].selectedIndex = 0;
		
		// For some reason the above doesn't call the onChange function
		// of the select box. So just call it on our own.
		changeTimeline($('#wbtl-admin-select').val());
	});	
}



// Utility function for showing the loading icon when we are requesting data from the server.
function setLoadingImage(element)
{
	element.html('<img src="http://www.google.com/ig/images/spinner.gif" />');
}




///////////////////////////////////////////////////////////////////////////////
//
// MAIN
//
///////////////////////////////////////////////////////////////////////////////


$(document).ready(function ()
{
	initTimeline();
	
	
	$('#wbtl-horizontal-bar')
		.css(
		{
			'overflow' : 'hidden' // change to hidden for JS users
		});

	$('img[class=wbtl-image]')
		// Control the scrollable from our own click handler since
		// adding and removing seems to screw up the navigator plugin on the timeline.
		.live('click', function ()
		{
			// Find the index of the button clicked.
			var listItem = $(this).parent().parent();
			var index = $('.wbtl-horiz-list>li').index(listItem);
			
			//alert("button " + index + " clicked");
			
			// Get handle to scrollable API and seek to the correct button.
			var api = $(".scrollable").data("scrollable");
			api.seekTo(index, 300);

		});

	
	// Scroll the timeline by clicking on a button.
	$('#wbtl-bottom-left-arrow')
		.live('click', function()
		{
			//$('#wbtl-horizontal-bar').attr('scrollLeft', $('#wbtl-horizontal-bar').attr('scrollLeft') + 190);
			$('#wbtl-horizontal-bar').animate(
			{
				scrollLeft: '-=164'
			},
			{
				duration:300,
				easing:'easeOutQuad'
			});
		});
	
	// Scroll the timeline by clicking on a button.
	$('#wbtl-bottom-right-arrow')
		.live('click', function()
		{
			var bar = $('#wbtl-horizontal-bar');

			if ((bar.attr('scrollLeft') + bar.attr('clientWidth') + 164) < bar.attr('scrollWidth'))
			{
				//$('#wbtl-horizontal-bar').attr('scrollLeft', $('#wbtl-horizontal-bar').attr('scrollLeft') - 190);
				$('#wbtl-horizontal-bar').animate(
				{
					scrollLeft: '+=164'
				},
				{
					duration:300,
					easing:'easeOutQuad'
				});
			}
		});

	// Saves the current button.
	$('.wbtl-admin-button-save')
		.live('click', function()
		{
			saveButtonInfo($(this));
		});

	// Adds a new button to the bottom bar.
	$('#wbtl-admin-add-bottom-button')
		.live('click', function ()
		{
			addBottomButton($('#wbtl-admin-select').val());
		});

	// Removes the current button.
	$('.wbtl-admin-button-remove')
		.live('click', function()
		{
			removeButton($(this));
		});

	// Changes between timelines
	$('#wbtl-admin-select')
		.change(function ()
		{
			changeTimeline($(this).val());
		});

	// Saves the settings for the timeline only. Not the buttons.
	$('#wbtl-admin-save')
		.click(function ()
		{
			saveSettings();
		});

	// Adds a brand new timeline.
	$('#wbtl-admin-addnew')
		.click(function ()
		{
			addNewTimeline();
		});

	// Removes the currently selected timeline.
	$('#wbtl-admin-remove')
		.click(function ()
		{
			removeTimeline($('#wbtl-admin-select').val());
		});
	
	// Adds a 'dirty' class to the item when it changes.
	$('input[name=button-order]')
	   .live('change', function()
	   {
	       // Only add the class if it isn't already there.
	       if (!($(this).hasClass('dirty')))
	       {
	           $(this).addClass('dirty');
	       }
	   });

	// Adds a 'dirty' class to the item when it changes.
	$('input[name=button-url]')
	   .live('change', function()
	   {
	       // Only add the class if it isn't already there.
	       if (!($(this).hasClass('dirty')))
	       {
	           $(this).addClass('dirty');
	       }
	   });

});

