

/**
 * Respond to an Ajax request's response
 * 
 * Requires data to contain
 * 	status: boolean true if successful request, false otherwise
 * 	content_array: array Contains arrays of id & html pairs to be inserted into dom
 * 
 * @param object data All our data from the php script
 * @param textStatus string The status of our ajax response
 * 
 * @since August 20, 2009
 */
function onAjaxResourceRetrieved(data, textStatus) {
	log('onAjaxResourceRetrieved.');
	log('Event data object:');
	log(data);
	
	if(data.success) {
		
		if(data.content_array) {
			
			for(var i = 0; i < data.content_array.length; i++) {
				
				var target_id = data.content_array[i].id;
				var html = unescape(data.content_array[i].html);
				
				// log('target_id:');
				// log(target_id);
				// log('html');
				// log(html);
				
				var oldHTML = String($('[id=' + target_id + ']').html());
				
				// log('old HTML:');
				// log('"' + oldHTML + '"');
				// 
				// log('new HTML:');
				// log('"' + html + '"');
				
				if(html !== oldHTML) {
					
					$('[id=' + target_id + ']').attr('new_html', html).
						animate({opacity:'0'}, 
							300, 
							function() { 
								$(this).html( $(this).attr('new_html') ).attr('new_html', null);
								if($(this).attr('AJAX_CONTENT_REFRESHED') == 'true') {
									$(document).trigger("AJAX_CONTENT_REFRESHED", data);
									$(this).attr('AJAX_CONTENT_REFRESHED', null);
									hidePreloaderGUI(700);
								}
								
								$(this).animate({opacity:'1'}, 700);
							});
					
					// We use a custom attribute to mark the last item that is re-written via ajax
					// This item will, when it's animation is completed, fire the event to re-init any js
					
					$('[id=' + target_id + ']').attr('AJAX_CONTENT_REFRESHED', 'true');
					if(i > 0) $('[id=' + data.content_array[i-1].id + ']').attr('AJAX_CONTENT_REFRESHED', null);
				}
			}
		}
		
		// Turn off the preloader progress gui
		//hidePreloaderGUI();
	}
	else {
		// This is weak...but it works for now.
		// When ajaxification fails because the template does not support it
		// then the results of the template are returned within the html param
		// There are no specific instructions about what to replace with what.
		// 
		// So we guess. Here we use the results of the html to do some dom rewriting
		// by looping through each item of the new html. If it contains a matching element
		// then we replace the old with the new. So, basically, we are replacing the entire
		// main content element (only if the current page and the new page both use the same element)
		// 
		// Not optimal ajax because it's basically rewriting the entire page
		// But it prevents the page from breaking completely for the end user
		//
		// A problem might arise when this is used to rewrite the dom and THEN
		// an ajax-enabled template is encountered that expects the dom to be in the
		// previous state. If we design the site properly this will not happen, but
		// the error could happen
		
		if(data.html) {
			// log('we have html...try to put into dom');
			var html = $( unescape(data.html) );
			
			// log('contains ' + html.length + ' items');
			// log(html);
			
			html.each( function() {
				// log(this);
					
				if(this.nodeName.toUpperCase() == 'DIV') {
					// log('div!');
					
					var selector = 'div';
					if($(this).attr('class')) {
						selector += '.' + $(this).attr('class');
					}
					if($(this).attr('id')) {
						selector += '#' + $(this).attr('id');
					}
					// log('selector:' + selector);
					var page_item = $(selector);
					// log(page_item);
					
					if(page_item.length > 0) {
						// log('will replace with:');
						// log($(this).html());
						page_item.html( $(this).html() );
					}
				}
			});
			
			// Turn off the preloader progress gui
			//hidePreloaderGUI();
		
		}
		
		// This is a sign of the new ajaxification, but a failed attempt
		
		else if(data.content_array) {
			if(data.ajaxlinkid) {
				$('a.ajax[id=' + data.ajaxlinkid + ']').attr('clicked', 'false');
			}
		}
	}
}

/**
 * Respond to an ajax link being clicked
 * 
 * @param event The jQuery event object
 * @return boolean false to stop the event from propagating
 */
function onAjaxLinkClicked(event) {
	
	if($(this).attr('clicked') == 'true') {
		event.stopPropagation();
		return false;
	}
	
	log('onAjaxLinkClicked');
	log(this);
	
	$(this).attr('clicked', 'true');
	
	var href = $(this).attr('href');
	log('href = ' + href);
	
	$('a.permalink').attr('href', href);
	
	// If the url contains parameters then break them off and send them
	// in the AJAX params variable
	
	var params = '&ajax=TRUE';
	if ( href.indexOf( "?") != -1)
	{
		var split = href.split("?");
		href = split[1];
		params += '&' + split[1];
	}
	params += '&ajaxlinkid=' + $(this).attr('id');
	
	log('params =');
	log(params);
	
	// Turn on the preloader gui
	displayPreloaderGUI(300);
	
	// We could use $.post(...) here, but YAHOO's YUI
	// recommends using GET because it sends 1 request to server
	// where POST sends 2 (1 for header, 1 for data)
	// http://developer.yahoo.com/performance/rules.html#ajax_get
	
	$.post( 'index.php', params, onAjaxResourceRetrieved, "json");
	
	event.stopPropagation();
	return false;
}

/**
 * Listen for new content to be inserted into the DOM
 * Run all our initialization code on the new HTML
 * to enable admin javascript on the new html
 */
function onAjaxContentRefreshed(event, data) {
	//log('onAjaxContentRefreshed');
	//log(data);
	
	// New HTML has been inserted into these elements
	// so we need to redo any javascript initialization to 
	// admin elements, cufon text, ajax links, etc.
	
	for(var i = 0; i < data.content_array.length; i++) {
		var target_id = data.content_array[i].id;
		
		// Initialize any ajax links within the new content
		
		$('a.ajax', '[id=' + target_id + ']').each( function() {
			$(this).attr('id', getRandomID());
			$(this).click( onAjaxLinkClicked );
		});
	}
	
	$('a.ajax[clicked=true]').attr('clicked', 'false');
}

/**
 * @work
 */
function hidePreloaderGUI(speed) {
	if(speed == null) speed = 300;
	var gui = $('#preloader_gui');
	if(gui) {
		gui.animate({opacity:'0'}, 
			speed, 
			function() { 
				$(this).css('display', 'none').css('opacity', '1');
			}
		);
	}
}

/**
 * @work
 */
function displayPreloaderGUI(speed) {
	var gui = $('#preloader_gui');
	if(gui) {
		if(speed == null) {
			gui.css('display', 'block');
		}
		else {
			gui.css('opacity', '0').css('display', 'block');
			gui.animate({opacity:'1'}, 
				speed, 
				function() { 
					// do stuff here if necessary
				}
			);
		}
	}
}

$(document).ready( function() {
	//log('will init the ajax link...');
	//log($('a.ajax'));
	
	$('a.ajax').each( function() {
		$(this).attr('id', getRandomID());
		$(this).click( onAjaxLinkClicked );
	});
	
	// Here we listen to for the AJAX content being refreshed so we
	// can run any initialization on the new content
	
	$(document).bind('AJAX_CONTENT_REFRESHED', onAjaxContentRefreshed);
	
	$('a.permalink').css('display', 'inline');
});

function getRandomID(length) {
	if(length == null) length = 8;
	var str = '';
	for ( ; str.length < length; str += Math.random().toString(36).substr(2) );
	return str.substr(0, length);
}
