/**
 * AJAX Nette Framwork plugin for jQuery (extended by Lubos Svoboda)
 *
 * @copyright   Copyright (c) 2009 Jan Marek
 * @license     MIT
 * @link        http://nettephp.com/cs/extras/jquery-ajax
 * @version     0.2
 */


/** Is any content easing? */
var easing = false;

jQuery.extend({
	nette: {
		updateSnippet: function (id, html) {
			$("#" + id).html(html);
		},

		success: function (payload) {
			// Redirect
			if (payload.redirect) {
				window.location.href = payload.redirect;
				return;
			}

			// Snippets & content easing
			if (payload.snippets) {
				// Ease content?
				if (payload.contentEase) {
					jQuery.nette.easeSection(payload);
				} else {
					// No, simply update HTML
					for (var i in payload.snippets) {
						jQuery.nette.updateSnippet(i, payload.snippets[i]);
					}
				}
			}
		},

		successForm: function (payload) {
			// Snippets
			if (payload.snippets) {
				for (var i in payload.snippets) {
					$("#writeus-form").html(payload.snippets[i]);
				}
			}
		},
		
		/** Ajax ease function (prevents Safari flickering) */
		easeSection: function (payload) {
			
			// Slides config
			slideWidth = 940;
			slidesMax = 2;
			
			// Snippets
			for (var i in payload.snippets) {
				html = payload.snippets[i];
				// Update only selected section
				if (i == 'snippet--section') {
					// Is any content easing?
					if (!easing) {
						// Prepare sections container for slides
						$('#sections-slider').css('width', slideWidth * slidesMax + 'px');
						// Add new slide as first node
						$('.section').before(html);
						// Refresh cufon
						Cufon.refresh();
						// Animate
						easing = true;
						$('.section').animate({
								'left' : - slideWidth + 'px'
							},{
								duration: 500,
								complete: function() {
									// Get section container back
									$('#sections-slider').css('width', slideWidth + 'px');
									// Remove old node
									$('.section:gt(0)').remove();
									// Set new node position
									$('.section').css('left', '0');
									easing = false;
							}
						});
					} else {
						// Stop, and instantly update with new content
						$('.section').stop(true, true);
						jQuery.nette.updateSnippet(i, html);
						// Refresh Cufon
						Cufon.refresh();
					}	
				} else {
					// Update non-easing content
					jQuery.nette.updateSnippet(i, html);
					// Refresh Cufon
					Cufon.refresh();
				}
			}
		}
	}
});

jQuery.ajaxSetup({
	success: jQuery.nette.success,
	dataType: "json",
	cache: false
});
