/****************************************
 * Aviary
 * App Dialog/Bar JavaScript
 ****************************************/

// Start closure to prevent namespace conflicts
;(function($) {

	// -----------------------------------
	// DomReady/window resize setup tasks
	// -----------------------------------
	$(document).ready(function() { $.AviaryDialogs.refresh(); });
	$(window).resize(function() { $.AviaryDialogs.refresh(); });		

	// -----------------------------------
	// General dialog/bar methods
	// -----------------------------------
	$.AviaryDialogs = {
		
		// Turn on the dark overlay progress indicator
		overlayOn: function(text) {
			var overlay = $('#appdialogs-overlay');
			var message = $('#appdialogs-overlay-text');
			var progress = $('#appdialogs-overlay-progress');
			var bg = $('#appdialogs-overlay-bg');
			
			// If no text is passed in for the message, use "Please wait ..."
			if(!text) {
				var text = 'Please wait ...';
			}
			// If we have text, make sure first letter is capitalized, add ellipsis
			else {
				text = text.substring(0, 1).toUpperCase() + text.substring(1) + ' ...';
			}
			
			overlay.css('height', $('#appdialogs').height());
			message.text(text);
			this.resetProgress(progress);
			bg.css('opacity', 0.85);
			overlay.fadeIn('fast');
		},
		
		// Turn off the dark overlay progress indicator
		overlayOff: function() {
			$('#appdialogs-overlay').fadeOut('fast');
		},
		
		// Set progress of a progress bar
		setProgress: function(progressElement, percent, onComplete) {
			var bar = $('.progress-fill', $(progressElement));
			var newWidth = percent * 1.25;
			bar.animate({ width: newWidth }, {duration: 'fast', complete: (typeof(onComplete) == 'undefined') ? false : onComplete});
		},
		
		// Reset a progress bar
		resetProgress: function(progressElement) {
			var bar = $('.progress-fill', $(progressElement));
			bar.width(0);
		},
		
		// Activate a dialog or bar and deactive the current one
		activate: function(what) {
			var current = $('.appdialog.active, .appbar.active');
			var target = $('#'+what);
			
			if(current.length == 1 && target.length == 1) {
				this.exchange(current, target);
			}
		},
		
		// Activate a tab (and its content) within the currently active dialog
		activateTab: function(tab, content) {
			var dialog = $('.appdialog.active');
			var newTab = $(tab);
			var tabs = newTab.parents('.appdialog-tabs');
			var oldTab = $('.active', tabs);
			var newContent = $('#'+content);
			var oldContent = $('.tabContent.active', dialog);
			
			// Activate the new content and deactivate the old
			this.exchange(oldContent, newContent);
			
			$('#appdialogs-inner').css('width', '100%');
			//alert($('#appdialogs-inner').css('width'));
			
			// ... and the tabs
			oldTab.removeClass('active');
			newTab.addClass('active');
		},

		// Helper function to exchange two "activatable" elements
		exchange: function(current, target) {
			// Show and hide the target to make sure it animates properly
			target.show().hide();

			// Slide the current one up and the new one down
			current.stop(true, true);
			target.stop(true, true);
			current.slideUp('fast', function() {
				target.slideDown('fast');
			});
		
			// Move the .active class to the new one
			current.removeClass('active');
			target.addClass('active');
		},
		
		// 
		// Setup stuff
		//
		
		// Setup tasks to perform whenever the document loads or window resizes
		refresh: function() {
			this.setMaxHeight();
			this.setAppSizer();
		},
		
		// Set the max height of the #appdialogs wrapper 
		// element so that scrolling kicks in when needed
		setMaxHeight: function() {
			$('#appdialogs').css('maxHeight', $(window).height());
		},
		
		// Set the height of the app sizer, which creates boundaries for the app to fill
		setAppSizer: function() {
			// The height is the size of the window minus 40px for the savebar
			$('#appsizer').css('height', $(window).height() - 40);
		}
		
	};

	// -----------------------------------
	// Save bar
	// -----------------------------------
	$.AviarySaveBar = {
		
		// Set state ("unsaved", "saved", "saving")
		setState: function(state, params) {
			// Get some elements
			var savebar = $('#savebar');
			var content = $('#savebar-content')
			var title = $('#savebar-title');
			var datetime = $('#savebar-datetime');
			var link = $('#savebar-link');
						
			// If the new state differs from the current state
			if(!savebar.hasClass(state)) {			
				// Temporarily hide the savebar
				content.fadeOut('fast', function() {				
					// Set the class to reflect the new state
					savebar.removeClass('unsaved saved saving unsavedswitching'); // add any new states here
					savebar.addClass(state);
					// Show the new savebar
					content.fadeIn('fast');
				});
			}
			
			// Do state-specific stuff:
			
			// Unsaved
			if(state == 'unsaved') {
				title.text('Untitled');
			}
			
			// Saved
			else if(state == 'saved') {
				title.text(params.title);
				datetime.text(params.datetime);
				
				if(params.url != 'donotset') {
				    document.getElementById("savebar-link").onclick = function () {
                       var x = window.open(params.url,'win', 'menubar=1,location=1'); // do your stuff
                      return false; // <-- to suppress the default link behaviour
                    };
                }

				
				// show the "overwrite" button in the save as dialog
				$('#saveas-aviary-overwrite').show();
			}
			
			// Saving
			else if(state == 'saving') {
				title.text(params.title);
				$.AviaryDialogs.setProgress('#savebar-saving .progress', params.percent, params.onComplete);
			}
		},
		
		// Save the current creation
		save: function() {
		
			// Reset the progress bar
			$.AviaryDialogs.resetProgress('#savebar-saving .progress');
			
			// Set the state to 'saving'
			this.setState('saving', {percent: 0});
			
			// Tell the Flash app to save the creation ...
			AviaryChannel.save();
		},
		
		
		// Save the current creation
		commit: function() {
            AviaryChannel.commit();
		}
	};

	// -----------------------------------
	// "Save as" dialog
	// -----------------------------------
	$.AviarySaveDialog = {
		// "Save as a new creation"
		saveAsNew: function() {
			this.startSave('new');
		},

		// "Overwrite 'My Creation' with new settings"
		saveOver: function() {
			this.startSave('overwrite');
		},

		// Functionality common to both save operations
		startSave: function(operation) {

			// Collect save settings
			var settings = { 'operation': operation };
			
			var elements = $('#permissionsForm select, #permissionsForm input')
									.add('#licenseForm select, #licenseForm input')
									.add('#saveas-aviary .column textarea, #saveas-aviary .column input')
									.not('input:radio:not(:checked)')
									.not('input:checkbox:not(:checked)');
									
			elements.each(function() {
				var element = $(this);
				settings[element.attr('id')] = element.val();
			});

			// Show the overlay progress indicator
			$.AviaryDialogs.overlayOn('saving');

			// Send settings data to the Flash app ...
			// console.log(settings);
			
			AviaryChannel.saveAs( settings );
		}
	};
	
	
	// Function: AviaryAjaxShow
// Show the AJAX indicator
// Example: $.AviaryAjaxShow();
$.AviaryAjaxShow = function() {
	// Show indicator
	$('#aviaryAjax').show();
	
	// For IE6, move the indicator when the window scrolls (and loads)
	if($.browser.msie && $.browser.version.charAt(0) == 6) {
		$(window).bind('scroll', moveAjax);
		moveAjax();
	}
}

// Function: AviaryAjaxHide
// Hide the AJAX indicator
// Example: $.AviaryAjaxHide();
$.AviaryAjaxHide = function() {
	// Hide indicator
	$('#aviaryAjax').hide();
	
	// Remove IE6 scroll event
	if($.browser.msie && $.browser.version.charAt(0) == 6) {
		$(window).unbind('scroll', moveAjax);
	}
}

// Helper function to move AJAX indicator for IE6
function moveAjax() {
	$('#aviaryAjax').css('top', $(window).scrollTop());
}

// End closure
})(jQuery);
