/*
	Copyright (c) JB Interactive Pty. Ltd.
	All Rights Reserved
	http://www.jbinteractive.com.au/
*/

(function ($) {

$(document).ready(function () {
	
	// Domain to reference unilink images and links from
	var domainName = 'dusabookshop.com.au';
	
	// Fix for IE lack of :hover support.
	$('#cart, #nav li')
		.hover(
			function () { $(this).addClass('over'); },
			function () { $(this).removeClass('over'); }
		);
	
	// Print button
	$('#print_list').click(function (e) {
			e.preventDefault();
			window.print();
			return false;
		});
	
	// Add item button
	$('#add_item').click(function () {
			var newitem = $item.clone(true);
			$('div.item:last').after(newitem);
			/*var $delete_button = $('div.item:last').find('.delete_item');
			var $delete_click = $delete_button.click();*/
			$('div.item:last')
				.hide()
				.slideDown("slow", function() {
					//$delete_button.click($delete_click);
				});
		});

	// Delete item button
	$('.delete_item').click(function () {
		
		var $this = $(this);
		
		/* The item is split into 3 sections:
		 *   The item itself, a div containing the remaining two sections,
		 *	 The item_inner div, containing the form divs
		 *	 The actions div, containing the delete/undo actions
		 */
		var item = $this.parents('.item');
		var item_actions = $this.parent();
		var item_inner = item_actions.siblings('div.item_inner');
		
		// Get the item's deleted input
		var $deleted = item_inner.find('input[id=item_deleted]');
		
		// If this is the new list form, delete the item immediately.
		if( ! $deleted.is('*') )
		{
			item.slideUp("slow", function() {
				item.remove();
			});
			
			return;
		}
		
		// If the item has been deleted, undelete it.
		if( $deleted.val() == 1 )
		{
			// Set the deleted property of the item
			$deleted.val(0);
			
			// Put the item back the way it was
			//item.css('height', 'inherit');
			
			// Make form fields visible again
			item_inner.slideDown("slow");
			
			
			// Delete the deleted message
			$this.siblings('div.deleted_message').fadeOut("fast", function() {
				$this.siblings('div.deleted_message').remove();
			});
			
			// Fade out the undo button
			$this.fadeOut("fast", function() {
				var caption = 'Delete Book';
				
				// If we are on the announcements page the caption is different
				if ($('#announcement_view').is('*')) {
					caption = 'Delete Announcement';
				}				
				
				// Change the caption of the delete button
				$this.html('<span><img src="/img/icons/delete.png"/> ' + caption + '</span>');
				// Make the delete button float right again
				$this.css("float", "right");
				// Fade it back in
				$this.fadeIn("fast");
			});
			
		}
		// Otherwise, delete the item.
		else
		{
			// Get the name of the item
			var itemname = item_inner.find('input[name="item_title[]"]').val();
			
			// If we are on the announcements page the name is just a static title
			if ($('#announcement_view').is('*')) {
				itemname = 'Announcement';
			}
			
			// Set the deleted property of the item
			$deleted.val(1);
			
			// Hide all of the item's form field elements
			item_inner.slideUp("slow");
			
			// Fade out the delete button
			$this.fadeOut("fast", function() {
				// Create the deleted message
				var deleted_message = '<div class="deleted_message" style="display: none">' +
				'<span style="font-weight: bold; font-style: italic;">' + itemname + '</span> has been deleted.</div>';
				// Add a big message saying that the item was deleted.
				$this.before(deleted_message);
				var message = $this.siblings('.deleted_message');
				// Change the float style to left
				$this.css("float", "left");
				// Change the caption of the delete button
				$this.html('<span><img src="/img/icons/undo.png"/> Undo</span>');
				// Fade in the message and the button
				message.fadeIn("fast");
				$this.fadeIn("fast");
			});
		}
	});

	$('a.button').click(function () {
		$(this).parents('form').trigger('submit');
	});
	
	var flashDuration = 300;
	var flashIcon = $('<img />').attr('src', '/img/icons/accept.png');
	var flashWarning = $('<img />').attr('src', '/img/icons/exclamation.png');
	
	var flashWarningFeedback = function(message, undoMethod) {
		flashFeedback(message, undoMethod, 'feedback-warning', flashWarning.clone());
	};
	
	var flashFeedback = function (message, undoMethod, extraClass, altImage) {
		var container = $('<div />').addClass('flash_message'),
			alert = $('<div />').addClass('feedback').css('margin', '0 auto 0 auto'),
			img = flashIcon.clone(),
			paragraph = $('<p />').addClass('last').html(message),
			oldMessages = $('.flash_message');

		if (undoMethod != null) {
			var undoLink = $('<a href="#" />').text('Undo.').click(undoMethod);
			paragraph.append(undoLink);
		}
		
		if (extraClass != null) {
			alert.addClass(extraClass);
		}
		
		if (altImage != null) {
			img = altImage;
		}

		container.append(alert.append(paragraph.prepend(img)));
		container.hide();
		
		var fadeContainerIn = function () {
			if (oldMessages.is('*')) {
				oldMessages.remove();
			}		
			$('.flash_messages').append(container);	
			container.fadeIn(flashDuration);
		};
		
		if (oldMessages.is('*')) {
			oldMessages.fadeOut(flashDuration, fadeContainerIn);
		} else {
			fadeContainerIn();
		}
	}
	
	// Ajax publish functionality.
	var publish = {
		
		method: function () {
			var $this = $(this);
			var chk = $this.attr('checked') ? 1 : 0;

			publish.lastPublished = $this;

			$.post($('form#lists').eq(0).attr('action') + "/publish", {
					id: $this.attr('name'),
					state: chk
				}, function (json) {
					flashFeedback(
						publish.formatMsg(json.name, json.state), 
						publish.undo
					);
				}, 'json');
		},
		
		undo: function (e) {
			e.preventDefault();
			
			var checked = publish.lastPublished.attr('checked');
			var state = (checked) ? 0 : 1;
			
			publish.lastPublished.attr('checked', !checked);
			
			$.post($('form#lists').eq(0).attr('action') + "/publish", {
					id: publish.lastPublished.attr('name'),
					state: state
				}, function (json) {
					$('.flash_message').fadeOut(flashDuration, function () {
						$(this).remove();
					});
				}, 'json');			
		},
		
		formatMsg: function(name, state) {
			if (state == 'published') {
				return '<b>' + name + '</b> has been published.';
			} else {
				return '<b>' + name + '</b> has been unpublished.';
			}
		}
		
	};
	
	// Ajax delete list functionality.
	var deleteLists = {
		
		init: function () {
			$('.delete_action').click(deleteLists.remove);
		},
		
		remove: function (e) {
			e.preventDefault();
			
			var row = $(this).parents('tr'), listId = row.attr('id');
			
			deleteLists.lastDeleted = { id: listId, row: row };
			
			row.fadeOut('slow');
			
			$.post($('form#lists').eq(0).attr('action') + '/delete', {
				id: listId
			}, function (json) {
				if (json.removed == '1') {
					flashWarningFeedback(
						deleteLists.formatMsg(json.name), 
						deleteLists.undo
					);				
				}
			}, 'json');
		},
		
		undo: function (e) {
			e.preventDefault();
			
			$.post($('form#lists').eq(0).attr('action') + '/restore', {
				id: deleteLists.lastDeleted.id
			}, function (json) {
				if (json.restored == '1') {
					deleteLists.lastDeleted.row.attr('id', json.id)
						.find('input[type=hidden]')
						.attr('name', json.id).end()
						.find('input[type=checkbox]')
						.attr('name', json.id)
						.attr('id', 'List_' + json.id).end()
						.find('label')
						.attr('for', 'List_' + json.id).end()
						.find('.email_action')
						.attr('href', '/admin/specials/email/id/' + json.id).end()
						.find('.edit_action')
						.attr('href', '/admin/specials/email/id/' + json.id).end()
						.fadeIn('slow');
					
					$('.flash_message').fadeOut(flashDuration, function () {
						$(this).remove();
					});					
				}
			}, 'json');			
		},
		
		formatMsg: function (name) {
			return '<b>' + name + '</b> has been deleted.';
		}
		
	};
	
	if ($('.delete_action').is('*')) {
		deleteLists.init();
	}
	
	$('input.publish').click(publish.method);
	
	// Drag-and-drop
	var makeDragAndDrop = function (form, tableSelector, formatMsg) {
		var reorder = { 

		 	options: {
				onDragStart: function (table, row) {
					reorder.previousState = reorder.table.html();
					reorder.previousOrder = $.tableDnD.serialize();
				},

				onDrop: function(table, row) {
					var post_data = $.tableDnD.serialize();
					$.post($('form#' + form).attr('action') + "/reorder", 
						post_data, 
						function (json) {
							if (json.reordered == '1') {
								flashFeedback(
									formatMsg($(row)), 
									reorder.undo
								);
							}
						}, 'json');
				}
			},

			undo: function (e) {
				e.preventDefault();

				reorder.table.html(reorder.previousState);
				reorder.table = $(tableSelector).tableDnD(reorder.options);

				$.post($('form#' + form).attr('action') + "/reorder", 
					reorder.previousOrder, 
					function (json) {
						$('.flash_message').fadeOut(flashDuration, function () {
							$(this).remove();
						});					
					}, 'json');			
			}

		};	
		
		reorder.table = $(tableSelector).tableDnD(reorder.options);
	};
	
	// Drag-and-drop lists
	makeDragAndDrop('lists', 'table.specials_list', function (row) {
		var text = row.find('label').text();
		
		if (text.lastIndexOf('(') != -1) {
			text = text.substr(0, text.lastIndexOf('('));
		}
		
		return '<b>' + text + '</b> has been re-arranged.';
	});
	
	// Drag-and-drop trimesters
	makeDragAndDrop('trimesters', 'table.trimesters_list', function (row) {
		return '<b>' + row.find('label').text() + '</b> has been re-arranged.';
	});
	
	// Ajax change trimester year functionality.
	var updateYear = {
	
		method: function (formatMsg) {
			var $this = $(this), newYear = $this.val();
			
			updateYear.previousUpdate = $this;

			$.post($('form#trimesters').attr('action') + "/change-year", {
					id: $this.parents('tr').attr('id'),
					year: newYear
				}, function (json) {
					if (json.changed == '1') {
						flashFeedback(
							updateYear.formatMsg($this.parents('tr'), newYear), 
							updateYear.undo
						);
					}
				}, 'json');
		},
		
		undo: function (e) {
			e.preventDefault();
			
			updateYear.previousUpdate.val(
				updateYear.previousUpdate.data('lastValue')
			);
			
			$.post($('form#trimesters').attr('action') + "/change-year", {
				id: updateYear.previousUpdate.parents('tr').attr('id'),
				year: updateYear.previousUpdate.data('lastValue')
				}, function (json) {
					$('.flash_message').fadeOut(flashDuration, function () {
						$(this).remove();
					});
				}, 'json');			
		},
		
		formatMsg: function (row, year) {
			return 'The Year for <b>' + row.find('label').text() + 
				'</b> has been changed to <b>' + year + '</b>.';
		}
		
	};
	
	$('select.trimester_year').each(function () {
		var $this = $(this);
		$this.data('lastValue', $this.val()).bind('change', updateYear.method);
	});
	
	// Duplicate items functionality.
	var $item = $('.item:last').clone(true);
	
	// Remove the extra item
	$('.item:last').remove();
	
	// Link all site links on the unilink pages to this site
	$('.sitelink').each(function () {
		var $this = $(this), href = $this.attr('href');
		
		if (href.substr(0, 1) != '/') {
			href = '/' + href;
		}
		
		$this.attr('href', 'http://' + domainName + href);
	});
	
	// Set local site images to correct path on unilink pages
	$('.siteimg').each(function () {
		var $this = $(this), src = $this.attr('src');

		if (src.substr(0, 1) != '/') {
			src = '/' + src;
		}
		
		$this.attr('src', 'http://' + domainName + src);
	});
});

$(function () {
	
	var MAX_TWEETS  = 3, i = 0,
		user        = 'DUSABookshop',
		twitter_api = 'http://search.twitter.com/search.json?callback=?&result_type=recent&q=from:' + user,
		search_expr = /(http:\/\/[^ ]+)/, // Very simple URL matcher
		parent      = $('#twitter-feed'),
		container   = $('<ul class="twitter-feed" />');
	
	if (parent.length)
	{
		parent.addClass('loading');
		
		$.get(twitter_api, function (json) {
			parent.removeClass('loading').append(container);
			if (!json.results || !json.results.length) {
				container.append('<li><p class="text">No recent tweets! <a href="http://twitter.com/' + user + '">Check our profile page</a> for past news</p></li>')
			} else {
				$.each(json.results, function () {
					if (i++ >= MAX_TWEETS) {
						return false;
					}
				
					var ago  = Math.round((Date.now() - new Date(this.created_at)) / 1000 / 60 / 60 / 24),
						text = this.text,
						permalink = 'http://twitter.com/' + user + '/status/' + this.id_str;
				
					if (ago == 0) {
						ago = 'today'
					} else if (ago == 1) {
						ago = 'yesterday'
					} else {
						ago = ago + ' days ago'
					}
				
					container.append('<li><p class="text">' + text.replace(search_expr, '<a href="$1">$1</a>')
						+ '</p><p class="time"><a href="' + permalink + '">' + ago + '</a></p></li>');
				});
			}
		}, 'json');
	}
	
});

})(jQuery);

