$(document).ready(function() {
	
	
	
	var la_height = $('div#landing_article').height() -18;
	
	if ($('div#landing_article div.empty_panel').length > 0) {
		la_height = la_height + 8;
	}
	
	$("a#landing_article_trigger").fancybox({
		'zoomSpeedIn': 0,
		'zoomSpeedOut': 0,
		'overlayShow': true,
		'overlayOpacity': 0.7,
		'overlayColor': '#000',
		'hideOnContentClick': false,
		'frameWidth': 343,
		'frameHeight': la_height,
		'callbackOnShow': setupNewsBuddies,
		'callbackOnClose': function() {
			closeAllBubbles();
		}
	});
	
	
	$("a#landing_page_trigger, a.button.sign_in").fancybox({
		'centerOnScroll': false,
		'zoomSpeedIn': 0,
		'zoomSpeedOut': 0,
		'overlayShow': true,
		'overlayOpacity': 0.7,
		'overlayColor': '#000',
		'hideOnContentClick': false,
		'hideOnOverlayClick': false,
		'padding': 0,
		'frameWidth': 739,
		'frameHeight': 455,
		'callbackOnClose': function() {
			closeAllBubbles();
		}
	});
	
	$("a#landing_page_trigger").click();
	
	
	$("a#log_in_trigger").fancybox({
		'enableEscapeButton': false,
		'showCloseButton': false,
		'zoomSpeedIn': 0,
		'zoomSpeedOut': 0,
		'overlayShow': true,
		'overlayOpacity': 0.7,
		'overlayColor': '#000',
		'hideOnContentClick': false,
		'hideOnOverlayClick': false,
		'padding': 0,
		'frameWidth': 513,
		'frameHeight': 329,
		'callbackOnClose': function() {
			closeAllBubbles();
		}
	});
	
	$("a#log_in_trigger").click();
	
	
	
	if ($('div#landing_article').html() != undefined) {
		$("a#landing_article_trigger").click();
	}
	
	
		
	setupOutboundLinkTargets();
	
	
	/* AJAX Confirm
	------------------------------------------------------------------------------*/
	$('a.ajax_invite_buddy').click(function() {

		$.ajax({
			type: "GET",
			url: $(this).attr('href'),
			success: function(msg) {
				hideInviteBuddyOptions($('a[href=#obc_' + msg + ']'));
				setAsInvited($('a[href=#obc_' + msg + ']'));
				removeInviteAction($('a[href=#obc_' + msg + ']'));
			}
			
		});
			
		
		return false;
	});
	
	$('a.open_buddy_confirm').click(function() {
		
		showInviteBuddyOptions(this);
		return false;
		
	});
	
	$('a.cancel_invite_buddy').click(function() {
		hideInviteBuddyOptions(this);
		return false;
		
	});
	
	/*------------------------------------------------------------------------------*/
	
	function showInviteBuddyOptions(obj_link) {
		$(obj_link).parents('li').find('span.buttons').slideDown();
	}
	
	function hideInviteBuddyOptions(obj_link) {
		$(obj_link).parents('li').find('span.buttons').slideUp();
	}
	
	function setAsInvited(obj_link) {
		$(obj_link).parents('li').find('span.invite_text').text('Invited');
	}
	
	function removeInviteAction(obj_link) {
		$(obj_link).unbind('click');
		$(obj_link).click(function() {
			return false;
		});
	}
	
	
	/* Header Save Button
	------------------------------------------------------------------------------*/
	$('#header_save').click(function() {
		$('#dialogue_save').click();
		return false;
	});
	/*----------------------------------------------------------------------------*/
	
	
	
	$('a.confirm').click(function() {
		return confirm('Are you sure?');
	});
	
	
	/* Dragging and dropping (jQuery UI: sortable)
	------------------------------------------------------------------------------*/
	
	// Define the sortable options...
	var sortable_options = {
		delay: 150,
		revert: false,									// Slow move to new position (or back)
		placeholder: "ui-selected",			// class name of placeholder or drop zone
		opacity: 0.25,									// Fade back while dragging
		tolerance: 'intersect',					// Technique use to detect landing area
		forcePlaceholderSize: true,			// Forces the placeholder to have a size
		connectWith: ["#cc_3, #triple_container, #cc_2_standard_modules, #aux_module_area"],		// Connect containers
		
		stop: function(e,ui) {
			
			// When the triple module is full, swap the modules instead
			if ($('#triple_container div.module').length > 3) {
				$('#triple_container div.module:visible:last').replaceAll('.ft_triple_helper:first');
			} else {
				
				// Module dropped into triple module
				if ((ui.item).parents('#triple_container').length > 0) {
					
					// Ensure that the dropped module is the last in the set
					$(ui.item).appendTo('#triple_container');

				}
				
			}
			
			// Clean up
			$('.ft_triple_helper').remove();
			
			updateTriple(ui.item);
			
			// Save positional data			
			$.post('/newspaper/request_handlers/save_positions.php', {
				positions: getModulePositionData()
			});

		},
		
		items: 'div.module:not(.fixed)',
	
		update: function(e,ui) {
			
			// Prevent News in Pics from being dragged into the triple module
			if ($(ui.item).find('div.news_in_pictures').length > 0) {
				// Detect triple module target
				if ((ui.item).parents('#triple_container').length > 0) {
					$(this).sortable('cancel');
					$(ui.sender).sortable('cancel');
					$(ui.item).fadeTo(0, 1);
				}
				
			}


		},

		start: function(e,ui) {
			
			
			// Our marker - where we dragged from
			$(ui.helper).after('<div style="display:none" class="ft_triple_helper">test</div>');
			
		}
		
		//sort: function(e, ul) { fixColHeights(); }
	};
	
	// Make the containers sortable
	$("#triple_container").sortable(sortable_options);
	$("#cc_3").sortable(sortable_options);
	$("#cc_2_standard_modules").sortable(sortable_options);
	$("#aux_module_area").sortable(sortable_options);
	
	/*----------------------------------------------------------------------------*/

	/* Triple Module Setup
	------------------------------------------------------------------------------*/

	function updateTriple(item) {
		
		var	test = '';
		$('#triple_module_tabs ul').html(test);
		
		var on_class_name = '';
		var highlight_done = false;
		
		var triple_tab_counter = 1;
		$('#triple_container div.module').each(function() {
			
			tab_name = $(this).find('div.header_bar h2').html();
			
			if (!highlight_done) {
				if (item == false) {
					on_class_name = ' class="on"';
					item = true;
					highlight_done = true;
				} else {
					
					if (tab_name == $('#triple_container div.module:visible:last').find('div.header_bar h2').html()) {
						on_class_name = ' class="on"';
						highlight_done = true;
					}
					
				}
			}
			
			test += "<li class=\"tab_"+ triple_tab_counter +"\"><a"+on_class_name+" href=\"#\">" + tab_name + "</a></li>";
			$('#triple_module_tabs ul').html(test);
			
			on_class_name = '';
			
			triple_tab_counter++;
			
		});
		
		// If there are no modules in the triple
		if ($('#triple_container div.module').length == 0) {
			
			// Using html() instead of append() here to prevent duplicates
			$('#triple_container').html("<div class=\"empty_panel triple\"><p>Drag your chosen categories into this area.</p></div>");
			
		} else {
			$('#triple_container div.empty_panel.triple').remove();
		}

		$('#triple_module_tabs ul li:nth-child(1)').click(function() {
			showTripleTab(1);
			$('#triple_module_tabs a').removeClass('on');
			$(this).find('a').addClass('on');
			return false;
		});
		
		
		$('#triple_module_tabs ul li:nth-child(2)').click(function() {
			showTripleTab(2);
			$('#triple_module_tabs a').removeClass('on');
			$(this).find('a').addClass('on');
			return false;
		});
		
		$('#triple_module_tabs ul li:nth-child(3)').click(function() {
			showTripleTab(3);
			$('#triple_module_tabs a').removeClass('on');
			$(this).find('a').addClass('on');
			return false;
		});

		
		if (item != false) {
		
			// If a module has been dropped in the triple container
			if ($(item).parents('#triple_container').length > 0) {
				$('#triple_container div.module').hide();
				$(item).show();
			}
			
		}
	
	}	
	
	// Start on the first tab
	showTripleTab(1);
	$('#triple_module_tabs a').removeClass('on');
	//$(this).find('a').addClass('on'); // Commented out 12/12/2009
	updateTriple(false);
	
	
	function showTripleTab(tabIndex) {
		
		$('#triple_container div.module').hide();
		$('#triple_container div.module:nth-child(' + tabIndex + ')').show();
		
	}
	

	/*----------------------------------------------------------------------------*/

	
	/* Module Favicon Tabs
	------------------------------------------------------------------------------*/
	
	// Hide all module content, except that in the first tab
	$('div.module div.content:not(.item_1)').hide();
	
	$('div.header_bar a').find('img.off').show();
	$('div.header_bar a').find('img.on').hide();
	
	$('div.header_bar').find('a[href="#item_1"] img.off').hide();
	$('div.header_bar').find('a[href="#item_1"] img.on').show();
	
	// Bind click handlers to the Favicon tabs
	$('div.module ul.tabs li a').click(function() {
		
		$(this).parents('div.header_bar').find('img.off').show();
		$(this).parents('div.header_bar').find('img.on').hide();
		
		$(this).find('img.off').hide();
		$(this).find('img.on').show();
		
		// Show the corresponding tab content when clicked, hide the others
		var item = $(this).attr('href').substr(1);
		
		$(this).parents('.module').find('div.content:not(.'+item+')').hide()
		
		
		var panel_href = $(this).parents('.module').find('.' + item).find('a.loader').attr('href');
		
		if (panel_href) {
		
			var container = $(this).parents('.module').find('.' + item);
		
			container.load(panel_href, function() {
								
				container.find('div.add_remove a.plus').click(function() {
					$(this).parents('div.short_news').find('div.news_item:hidden:first').slideDown('fast');
					return false;
				});

				container.find('div.add_remove a.minus').click(function() {
					$(this).parents('div.short_news').find('div.news_item:visible:last').slideUp('fast');
					return false;
				});
				
				// Update the header for the loaded module
				$(this).find('h3:first').addClass('first');
				
				// Add class reference to first image in the module
				$(this).find('div.image:first').addClass('first');
				
				setupBubbles();
				setupNewsBuddies();
				setupOutboundLinkTargets();
				setupClipboard();

			});
			
		}
		
		$(this).parents('.module').find('.' + item).show();
		
		
		
	});
	
	
	
	
	/*----------------------------------------------------------------------------*/
	
	
	/* Short News Add / Remove Items
	------------------------------------------------------------------------------*/
	
	shortNewsSetup();
	
	/*----------------------------------------------------------------------------*/
	
	/* News in Pictures
	------------------------------------------------------------------------------*/
	
	// Hide all but the first caption
	$('div.news_in_pictures div.caption:first').fadeIn('slow');
	
	var nudge = 0;
	
	$('div.news_in_pictures div.image_container img').each(function() {
		nudge = nudge + $(this).width() + 7;		
	});
	
		
	$('div.caption').each(function() {
		$(this).attr('rel', parseInt($(this).attr('rel')) + nudge);
	});
	

	
	$('body').prepend('<div class="temp" style="display:none;"></div>');
	$('div.news_in_pictures div.image_container img').each(function() {
		$(this).clone().prependTo('body div.temp');
		$(this).clone().appendTo('div.news_in_pictures div.image_container');
	});
	$('body div.temp img').each(function() {
		$(this).clone().prependTo('div.news_in_pictures div.image_container');
	});
	$('body div.temp').remove();
	
	$('div.news_in_pictures div.image_container img').eq($('div.news_in_pictures div.image_container img').length / 3).addClass('current');
		
	
	$('div.news_in_pictures div.image_container').css('width', '10000px');
	$('div.news_in_pictures div.image_container').css('margin-left', 171 - parseInt($('div.news_in_pictures div.caption:first').attr('rel')) +'px');
	
	

	$('div.news_in_pictures div.image_container img').fadeIn('slow');
	
	
	document.nip_transition = false;
	
	// When the next button is clicked
	$('div.news_in_pictures div.navigation a.next').click(function() {
		
		if (!document.nip_transition) {
		
			var imageMargin = 7;
			
			// Determine the current
			var current = $(this).parents('div.news_in_pictures').find('div.caption:visible');
			
			// Default to the first image in the set
			var next = $(this).parents('div.news_in_pictures)').find('div.caption:first');
			
			// Image details and positions
			var cur_pos = parseInt($('div.news_in_pictures div.image_container').css('margin-left'));
			
			var cur_img = $('div.news_in_pictures div.image_container img.current');
			var cur_img_width = cur_img.width();
			
			var next_img = cur_img.next('img');
			var next_img_width = next_img.width();
			
			var offset_pos = (cur_img_width / 2) + (next_img_width / 2) + imageMargin;
						
			// Calculate the next position
			next_pos = cur_pos - offset_pos;
	
			
			// Next image should be the next sibling, should it exist...
			if ($(current).next('div.caption').length != 0) {
				next = $(current).next('div.caption');
			}
			
			// Perform the fade in/out
			current.fadeOut('fast', function() {
				next.fadeIn('slow');	
			});
			
			cur_img.removeClass('current');
			next_img.addClass('current');
			
			document.nip_transition = true;
			$('div.news_in_pictures div.image_container').animate( { marginLeft: next_pos +'px' }, 750, function() {
				
				
				// Make a copy of the image image, put it at the end
				$('div.news_in_pictures div.image_container img:first').clone().appendTo('div.news_in_pictures div.image_container');
				
				// Adjust the margin to compensate for removed image
				$('div.news_in_pictures div.image_container').css('margin-left', parseInt($('div.news_in_pictures div.image_container').css('margin-left')) + imageMargin + $('div.news_in_pictures div.image_container img:first').attr('width'));
				
				// Remove the first image
				$('div.news_in_pictures div.image_container img:first').remove();
				
				document.nip_transition = false;
			
			});
		
		}

	});
	
	
	// When the previous button is clicked
	$('div.news_in_pictures div.navigation a.prev').click(function() {
		
		if (!document.nip_transition) {
		
			var imageMargin = 7;
			
			// Determine the current
			var current = $(this).parents('div.news_in_pictures').find('div.caption:visible');
			
			// Default to the first image in the set
			var next = $(this).parents('div.news_in_pictures)').find('div.caption:last');
			
			// Image details and positions
			var cur_pos = parseInt($('div.news_in_pictures div.image_container').css('margin-left'));
			
			var cur_img = $('div.news_in_pictures div.image_container img.current');
			var cur_img_width = cur_img.attr('width')
			
			var next_img = cur_img.prev('img');
			var next_img_width = next_img.attr('width')
			
			var offset_pos = (cur_img_width / 2) + (next_img_width / 2) + imageMargin;
			
			// Calculate the next position
			next_pos = cur_pos + offset_pos;
	
			
			// Next image should be the next sibling, should it exist...
			if ($(current).prev('div.caption').length != 0) {
				next = $(current).prev('div.caption');
			}
			
			cur_img.removeClass('current');
			next_img.addClass('current');
			
			// Perform the fade in/out
			current.fadeOut('fast', function() {
				next.fadeIn('slow');	
			});
			
			document.nip_transition = true;
			$('div.news_in_pictures div.image_container').animate( { marginLeft: next_pos +'px' }, 750, function() {
				
				// Make a copy of the last image, put it at the end
				$('div.news_in_pictures div.image_container img:last').clone().prependTo('div.news_in_pictures div.image_container');
				
				// Adjust the margin to compensate for removed image
				$('div.news_in_pictures div.image_container').css('margin-left', parseInt($('div.news_in_pictures div.image_container').css('margin-left')) - imageMargin - $('div.news_in_pictures div.image_container img:last').attr('width'));
				
				// Remove the first image
				$('div.news_in_pictures div.image_container img:last').remove();
				
				document.nip_transition = false;
			
			});
		
		}
		
	});

	
	/*----------------------------------------------------------------------------*/


	
	/* CSS Helpers
	------------------------------------------------------------------------------*/
	
	$('div.module div.content>div.news_item:last').addClass('last');
	$('div.triple_module>div.module div.content>div.news_item:last').addClass('last');
	
	$('div#page_selection ul li:first').addClass('first');
	$('div#page_selection ul li:eq(1)').addClass('row_two_top');
	
	$('div#page_selection ul.all li:first').addClass('first');
	$('div#page_selection ul.all li:eq(1)').addClass('row_two_top');	
	
	
	$('table.index tr:odd').addClass('altrow');
	
	$('div.module').each(function() {
		
		$(this).find('h3:first').addClass('first');
		$(this).find('div.image:first').addClass('first');
		
	});
	
	col_height_max = 600;
	$('div#cat_level_1 ul').each(function() {
		if ($(this).height() > col_height_max) col_height_max = $(this).height();
	});
	
	// Fix overflow of long cols
	$('div#cat_level_1,div#cat_level_2,div#cat_level_3').height(col_height_max);

	
	
	$('body.user_config div#cat_level_1').height(col_height_max);	
	$('body.user_config div#page_content').height(col_height_max); // For IE...
	
	
	/*----------------------------------------------------------------------------*/
	
	
	/* Helper Switches
	------------------------------------------------------------------------------*/
	if ($('body').hasClass('helpers')) {
		$('div#helper_switch').html('<a class="off no_follow" href="#helper_switch">Turn&nbsp;guidance&nbsp;off</a>');
		$('div#page_helper, div#select_page_helper').show();
	} else {
		$('div#helper_switch').html('<a class="on no_follow" href="#helper_switch">Turn&nbsp;guidance&nbsp;on</a>');
	}
	
	toggleHelpers();
	
	$('div#helper_switch').click(function() {
		
		if ($(this).find('a').hasClass('off')) {
			$(this).find('a').removeClass('off').addClass('on');
			$(this).find('a').html('Turn guidance on');
			toggleHelpers();
			$.post('/account/settings/misc/request_handlers/toggle_guidance.php', { state: 0 } );
		} else {
			$(this).find('a').removeClass('on').addClass('off');
			$(this).find('a').html('Turn guidance off');
			toggleHelpers();
			$.post('/account/settings/misc/request_handlers/toggle_guidance.php', { state: 1 } );
		}

		return false;
		
	});
	
	
	function toggleHelpers() {
		if ($('div#helper_switch').find('a').hasClass('on')) {
			helpersOn();
		} else {
			helpersOff();
		}
	}
	
	function helpersOn() {
		$('div.helper').each(function() {
			if (!$(this).hasClass('closed') && !$(this).hasClass('inactive')) {
				turnHelperOff(this);
			}
			
		});
	}
	
	function helpersOff() {
				
		$('div.helper').each(function() {
			if ($(this).hasClass('closed') && !$(this).hasClass('inactive')) {
				turnHelperOn(this);
			}
			
		});
	}

	function turnHelperOff(item) {		
		$(item).animate({opacity: 0, marginTop: -30}, null, 'swing', function() {
			$(item).addClass('closed');
			$(item).hide();
		});
	}
	
	function turnHelperOffInstantly(item) {
		$(item).hide();
		$(item).animate({opacity: 0, marginTop: -30}, 0.1);
		$(item).addClass('closed');
	}
	
	function turnHelperOn(item) {
		$(item).show();
		$(item).animate({opacity: 1, marginTop: -7}, null, 'swing', function() {
			$(item).removeClass('closed')
		});
	}
	
	function turnHelperOnInstantly(item) {
		$(item).show();
		$(item).animate({opacity: 1, marginTop: -7}, 0.1);
		$(item).removeClass('closed');		
	}
	
	/*----------------------------------------------------------------------------*/
	
	
	var count = 0;
	var limit = 16;
	
	$('div#selection_status span').html(limit);

	$('div#page_selection input').click(function() {
		if (!updatePageCount()) {
			$(this).attr("checked", false);
		}
	});
	
	function updatePageCount() {
	
		count = $('div#page_selection input:checked').length;
		
		if (count <= limit) {
			$('div#selection_status span').text(limit  - count);
			return true;
		} else {
			return false;
		}
	}
	
	updatePageCount();
	
	/*----------------------------------------------------------------------------*/
	
	/* User Settings: Categories
	------------------------------------------------------------------------------*/
	
	$('div#page_cats.cat_conf a').click(function() {
		
		if (document.browser_flag == 'non_ie') {
			$('#suggest_a_feed').fadeOut();
		} else {
			$('#suggest_a_feed').hide();
		}
		
		$('div#select_page_helper').addClass('inactive');
		turnHelperOff($('div#select_page_helper'));
		
		$('div#pub_sort_helper').addClass(' inactive');
		turnHelperOff($('div#pub_sort_helper'));
		
		if (document.browser_flag == 'non_ie') {
			$('div#cat_level_2 div.header').fadeOut();
			$('div#cat_level_2 div.cat_pubs').fadeOut();
		} else {
			$('div#cat_level_2 div.header').hide();
			$('div#cat_level_2 div.cat_pubs').hide();
		}
		
		$('div#tick_categories_helper').removeClass('inactive');

		toggleHelpers();
		
		if (document.browser_flag == 'non_ie') {
			$('div#cat_level_1>ul, div#cat_level_2>ul, div#cat_level_3>ul').fadeOut();
		} else {
			$('div#cat_level_1>ul, div#cat_level_2>ul, div#cat_level_3>ul').hide();
		}
		
		$('div#page_cats a').removeClass('active');
		$(this).addClass('active');
		
		if (document.browser_flag == 'non_ie') {
			$($(this).attr('href')).fadeIn();
		} else {
			$($(this).attr('href')).show();
		}
		
		
		return false;
		
	});
		
	
	$('div#cat_level_1 a').click(function() {
		
		// Copy the keywords to the editor
		var keyword_container = $(this).parent().find('input.cat_keywords');		
		var keyword_container_default = $(this).parent().find('input.cat_keywords_default');
		var keywords = $(keyword_container).val();
		
		if (document.browser_flag == 'non_ie') {
			$('#suggest_a_feed').fadeIn();
		} else {
			$('#suggest_a_feed').show();
		}

		
		$('#cur_edit_ref').val(keyword_container.attr('name'));
		$('#cur_default_edit_ref').val(keyword_container_default.attr('name'));
		
		$('textarea#keyword_editor').val(keywords);
		
		$('#keyword_editor_title').html($(this).parent().find('label').html());
		
		$('div#tick_categories_helper').addClass('inactive');
		turnHelperOff($('div#tick_categories_helper'));
		
		$('div#pub_sort_helper').removeClass('inactive');
		
		toggleHelpers();
		
		if (document.browser_flag == 'non_ie') {
			$('div#cat_level_2>ul, div#cat_level_3>ul, div#cat_level_2>div.cat_pubs').fadeOut();
		} else {
			$('div#cat_level_2>ul, div#cat_level_3>ul, div#cat_level_2>div.cat_pubs').hide();
		}
		
		$(this).parents('ul').find('li').removeClass('active');
		$('div#cat_level_2 li').removeClass('active');
		$(this).parents('li').addClass('active');
		
		$($(this).attr('href')).find('ul').show();
		
		if (document.browser_flag == 'non_ie') {
			$($(this).attr('href')).fadeIn();
		} else {
			$($(this).attr('href')).show();
		}
		
		
		enableCatSorting($($(this).attr('href')).attr('id'));
		
		
		
		// Set the cat list title
		var cat_list_limit = 35;
		var cat_list_header_append = ' publishers';
		var cat_list_header_main = $(this).parent().find('label').html() + cat_list_header_append;

		var cat_list_header_main_ready = $.trim(cat_list_header_main.substring(0, cat_list_limit - 1));
		
		if (cat_list_header_main != cat_list_header_main_ready) {
			cat_list_header_main_ready += '...';
		}
		
		$('#cat_header').html(cat_list_header_main_ready);
		
		if (document.browser_flag == 'non_ie') {
			$(this).parents('div').find('div.header').fadeIn();
		} else {
			$(this).parents('div').find('div.header').show();
		}
		
		return false;
		
	});
	
	
	// KEYWORDS
	
	// Put the new keywords in appropriate hidden field
	$('#bt_save_keywords').click(function() {
		$('input[name=' + $('#cur_edit_ref').val() + ']').val($('textarea#keyword_editor').val());
		
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.keywords').fadeOut();
		} else {
			$('div.dialogue.keywords').hide();
		}
		
		document.changed = true;
		
		// serialise the keywords, add to save form
		$('#category_keywords').val($("input.cat_keywords").serialize());		
		return false;
	
	});
	
	// Revert button handler
	$('#bt_revert_keywords').click(function() {
		$('textarea#keyword_editor').val($('input[name=' + $('#cur_default_edit_ref').val() + ']').val());
		return false;
	});
	
	// Close Button handler
	$('div.dialogue a.bt.close').click(function() {
		if (document.browser_flag == 'non_ie') {
			$(this).parents('div.dialogue').fadeOut();
		} else {
			$(this).parents('div.dialogue').hide();
		}
		return false;
	});
	
	
	
	if ($('div.dialogue.notifications').hasClass('has_messages')) {
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.notifications').fadeIn();
		} else {
			$('div.dialogue.notifications').show();
		}
	}
	
	// Close Button handler
	$('div.dialogue.notifications a.bt.close, div.dialogue.notifications a#continue').click(function() {
		
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.notifications').fadeOut();
		} else {
			$('div.dialogue.notifications').hide();
		}
		
		var surpress_list = 'go=true&' + $('div.dialogue.notifications input').serialize();
		
		
		$.ajax({
			type: "POST",
			url: "/account/settings/misc/request_handlers/surpress_messages.php",
			data: surpress_list,
			success: function(msg){
				
			}
		});

		
		
		return false;
	});
	
	
	
	$('div#cat_level_2 a').click(function() {
				
		$('div#cat_level_2 li').removeClass('active');
		$(this).parents('li').addClass('active');
		
		if (document.browser_flag == 'non_ie') {
			$('div#cat_level_3>ul, div#cat_level_3>ul').fadeOut();
		} else {
			$('div#cat_level_3>ul, div#cat_level_3>ul').hide();
		}
		
		if (document.browser_flag == 'non_ie') {
			$($(this).attr('href')).fadeIn();
		} else {
			$($(this).attr('href')).show();
		}
		
		return false;
		
	});
	
	
	// Determine the height of the tallest column
	var maxHeight = 600;	
	if ($('div#cat_level_1 > ul').height() > maxHeight) maxHeight = $('div#cat_level_1 > ul').height();
	if ($('div#cat_level_2 > ul').height() > maxHeight) maxHeight = $('div#cat_level_2 > ul').height();
	if ($('div#cat_level_3 > ul').height() > maxHeight) maxHeight = $('div#cat_level_3 > ul').height();
	if ($('div.cat_pubs')) maxHeight += 32;
	
	// Hide the subsequent cols initially
	$('div#cat_level_2>ul, div#cat_level_3>ul, div#cat_level_2>div.header').hide();
		
	// Start with the helper closed and inactive
	// ******** 
	turnHelperOffInstantly($('div#tick_categories_helper'));
	$('div#tick_categories_helper').addClass('inactive');
	
	$('div#pub_sort_helper').addClass('inactive');
	turnHelperOffInstantly($('div#pub_sort_helper'));
	

	//$('div#cat_level_1 ul').hide();
	$('div.cat_pubs').hide();
	
	
	$('body.user_config div#cat_level_1').attr('style', 'height: ' + maxHeight + 'px !important');
	$('body.user_config div#cat_level_2').attr('style', 'height: ' + maxHeight + 'px !important');
	$('body.user_config div#cat_level_3').attr('style', 'height: ' + maxHeight + 'px !important');


	/*----------------------------------------------------------------------------*/
	
	
	$('a#open_keywords').click(function() {
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.keywords').fadeIn();
		} else {
			$('div.dialogue.keywords').show();
		}
		return false;
	});
	

		
	$('#fb_feed_search').flexbox('/admin/feeds/request_handlers/search.php', {
		showArrow: false,
		highlightMatchesRegExModifier: 'gim',
		onSelect: function() {
			window.location = '?id=' + this.getAttribute('hiddenValue');
		}
	}); 
	
	$('#fb_publisher_search').flexbox('/admin/publishers/request_handlers/search.php', {
		showArrow: false,
		highlightMatchesRegExModifier: 'gim',
		onSelect: function() {
			window.location = '?id=' + this.getAttribute('hiddenValue');
		}
	});
	
	$('#fb_category_search').flexbox('/admin/categories/request_handlers/search.php', {
		showArrow: false,
		highlightMatchesRegExModifier: 'gim',
		onSelect: function() {
			window.location = '?id=' + this.getAttribute('hiddenValue');
		}
	});
	
	$('#fb_user_search').flexbox('/admin/users/request_handlers/search.php', {
		showArrow: false,
		highlightMatchesRegExModifier: 'gim',
		onSelect: function() {
			window.location = '?id=' + this.getAttribute('hiddenValue');
		}
	});
	
	$('input.to_replace').hide();
	$('a.button.replacement').click(function() {
		$($(this).attr('href')).click();
		return false;
	});
	
	
	$(".tooltip").jHelperTip({
	 trigger: "hover",
	 source: "attribute", 
	 attrName: "rel", 
	 autoClose: true, 
	 opacity: 0.9
	});
			
	$('.del_module').click(function() {
		
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.module.delete').fadeIn();
		} else {
			$('div.dialogue.module.delete').show();
		}
		document.delete_module_ref = this;
	});
	
	$('div.dialogue.module.delete a#dialogue_save').click(function(){
		
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.module.delete').fadeOut();
		} else {
			$('div.dialogue.module.delete').hide();
		}
		$(document.delete_module_ref).parents('div.module').remove();
		
		updateTriple(false);

		// Save positional data			
		$.post('/newspaper/request_handlers/save_positions.php', {
			positions: getModulePositionData()
		});
		
		return false;
		
	});
	
	$('div.dialogue.delete a#dialogue_revert').click(function(){
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.delete').fadeOut();
		} else {
			$('div.dialogue.delete').hide();
		}
	});
	
	
		
	$('div.publishers_available_wrapper').css('overflow', 'auto');
	
	setupBubbles();
	
	// close button handler
	$('div.bubble a.close').click(function() {
		
		if (document.browser_flag == 'non_ie') {
			$(this).parent().fadeOut();
		} else {
			$(this).parent().hide();
		}
		
		return false;
		
	});
	
	
	// Image rotator
	rotate_images();
	
	
	$('div.dialogue.delete a.bt.close').click(function() {
	
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.delete').fadeOut();
		} else {
			$('div.dialogue.delete').hide();
		}
		
		return false;
		
	});
	
	$('div.dialogue.cancel_account a.bt.close, a#dialogue_cancellation_back').click(function() {
	
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.cancel_account').fadeOut();
		} else {
			$('div.dialogue.cancel_account').hide();
		}
		return false;
	});
	
	
	$('a#bt_cancel_account').click(function() {
	
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.cancel_account').fadeIn();
		} else {
			$('div.dialogue.cancel_account').show();
		}
		
		return false;
		
	});
	
	$('a#dialogue_confirm_cancellation').click(function() {
		$(this).parents('form').submit();
	});
	
	
	
	// Generic checkbox select all
	var select_all = $('input[type="checkbox"].select_all');

	
	select_all.change(function() {
		
		var all_boxes = $(this).parents('form').find('input').not(select_all);
		
		// When select all is checked, check all checkboxes
		if ($(this).attr('checked')) {
			all_boxes.attr('checked', true);
		} else {
			all_boxes.attr('checked', false);
		}
	});
		
	
	// News Buddies Comments	
	$('div.nb_story').find('div.comment:last').addClass('current').each(function() {
		if ($(this).hasClass('hl')) {
			markCurrentAsRead($(this));
		}
	});
	
	function markCurrentAsRead(story_ref) {
		
		var read_url = '/account/settings/news_buddies/request_handlers/mark_comment_as_read.php';
		
		if (!story_ref.hasClass('read')) {			
			$.post(read_url, { read_comment: parseInt(story_ref.attr('id').replace('comment_', '')) });
		}

		story_ref.addClass('read');
		
	}
	
	
	
	/* News Buddies
	----------------------------------------------------------------------------*/
	
	$('a.bt_nb_reply').click(function() {
		parent.openNBReply(this);
		return false;
	});
	
	setupNewsBuddies();
	
	// Accept / Reject News Buddy
	$('div.nb_element_buttons a.accept, div.nb_element_buttons a.reject').click(function() {
		
		var inviter_id = parseInt($(this).attr('href').replace('#', ''));
		var confirm_url = '/account/settings/news_buddies/request_handlers/confirm.php';
		
		var nb_action = 'reject';
		if ($(this).hasClass('accept')) nb_action = 'accept';
		
		$.get(confirm_url, { action: nb_action, buddy_id: inviter_id }, function() { });
		
		$(this).parents('div.nb_element').slideUp(function(){	
			$(this).remove();
		});
		
	});
	
	
	// View News Buddy Message
	newsBuddyModal($("a.view_story"), 'view');
	

	// Make the whole area clickable
	$('div#news_buddy_bar div.nb_element.story').click(function() {
		$(this).find('a.view_story').click();
	});
	
	
	
	// Deleting a story
	
	$('a.bt.close.del_nb_story').click(function() {
		
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.delete.story').fadeIn();
		} else {
			$('div.dialogue.delete.story').show();
		}
		
		
		
		document.delete_nb_story_ref = this;

		return false;
	});
	
	$('div.dialogue.delete.story a#dialogue_del_story').click(function(){
		
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.delete.story').fadeOut();
		} else {
			$('div.dialogue.delete.story').hide();
		}
		
		deleteNewsBuddyStory($(document.delete_nb_story_ref).attr('href').replace('#', ''));
		
		$(document.delete_nb_story_ref).parents('div.nb_element.story').slideUp();
		
		$(document.delete_nb_story_ref).parents('div.nb_story').remove();
		
		$(document.delete_nb_story_ref).parents('div.buddy_story').remove();
		
		return false;
		
	});
	
	$('div.dialogue.delete.story a#dialogue_revert').click(function(){
		if (document.browser_flag == 'non_ie') {
			$('div.dialogue.delete.story').fadeOut();
		} else {
			$('div.dialogue.delete.story').hide();
		}
	});
	
	
	function deleteNewsBuddyStory(id) {
		
		var story_counter = parseInt($('span.display_total_stories').html());
		
		if (story_counter-- > 0) {
			$('span.display_total_stories').html(story_counter);
		}
		
		var delete_url = '/account/settings/news_buddies/request_handlers/delete_story.php';
		$.get(delete_url, { id: id }, function() { });
	}
	
	/*--------------------------------------------------------------------------*/
	
	$('textarea[maxlength]').keydown(function() {
		
		if ($(this).val().length > 100) {
			$(this).val($(this).val().substring(0, 100));
		}
		
	});
	
	
	$('div.bubble.notification a').click(function() {
		
		if (document.browser_flag == 'non_ie') {
			$('div#save_changes_message').fadeOut();
		} else {
			$('div#save_changes_message').hide();
		}
		
		var surpress_list = "";
		
		switch($(this).attr("id")) {
			case 'personalise_message':
				surpress_list = 'go=true&notifications[]=6';
			break;
			case 'favicons_info':
				surpress_list = 'go=true&notifications[]=8';
			break;
			case 'organise_categories':
				surpress_list = 'go=true&notifications[]=9';
			break;
			case 'top_5_publishers':
				surpress_list = 'go=true&notifications[]=10';
			break;
			case 'search_folders':
				surpress_list = 'go=true&notifications[]=12';
			break;
		}
		
		$.ajax({
			type: "POST",
			url: "/account/settings/misc/request_handlers/surpress_messages.php",
			data: surpress_list
		});
		

		return false;

	});
	
	
	if (!areThereOpenModals()) {
		$('#new_feature').fancybox({
			'padding': 0,
			'zoomSpeedIn': 0,
			'zoomSpeedOut': 0,
			'overlayShow': true,
			'overlayOpacity': 0.7,
			'overlayColor': '#000',
			'hideOnContentClick': false,
			'hideOnOverlayClick': false,
			'frameWidth': 742,
			'frameHeight': 402,
			'showCloseButton': false,
			'callbackOnShow': function() {
				$('#fancy_title').hide();
				
				 $('a.ajax_action_close').click(function() {
					
					$.ajax({
						type: "GET",
						url: $(this).attr('href')
					});
					
					closeAllModals();
					
					return false;
				 });
				
			}
		});
	}

	$('#new_feature').click();
	
	
	
	
	
		
	setupClipboard();
	
		
});

function setupClipboard() {
		$('a.ft_icon.clipboard').click(function() {
			
			var action = 'add';
			if ($(this).hasClass('remove')) {
				action = 'remove';
			}
			
			$.ajax({
				type: "GET",
				url: "/admin/mailer/request_handlers/toggle_item_on_clipboard.php",
				data: "article_id=" + $(this).attr('href').replace('#', '') +'&action=' + action,
				success: function() {
					
					return false;
				
				}
				
			});
			
			if (action == 'add') {
				$(this).addClass('remove');
			} else {
				$(this).removeClass('remove');
			}

			return false;
		});
	}

function openNBReply(bt_ref) {
	
	
	if (document.browser_flag == 'non_ie') {
		$('div.nb_reply').fadeIn();
	} else {
		scroll(0,0);
		$('div.nb_reply').show();
	}
	
	$('div.nb_reply iframe').attr('src', '/account/settings/news_buddies/stories/reply.php?id=' + $(bt_ref).attr('href').replace('#', ''));
}

function closeNBReply() {
	if (document.browser_flag == 'non_ie') {
		$('div.nb_reply').fadeOut(function() {
			$('div.nb_reply').hide();
		});
		$('div.nb_view').fadeOut(function() {
			$('div.nb_view').hide();
		});
	} else {
		$('div.nb_reply').hide();
		$('div.nb_view').hide();
	}
}

function closeNBSend() {

	if (document.browser_flag == 'non_ie') {
		$('div.nb_send').fadeOut(function() {
			// Just in case box doesn't fade out properly
			$('div.nb_send').hide();
		});
	} else {
		$('div.nb_send').hide();
	}
}

function setupNewsBuddies() {
	
	newsBuddyModal($('a.ft_icon.buddy').not('.account_required'), 'create');
		
	$('a.ft_icon.buddy.hover_dialogue').not('.account_required').click(function() {
		parent.nbSendStory(0, $(this).attr('href').replace('#', ''), false, 0);
		return false;
	});
	
	$("div#news_buddy_bar a.view_story").click(function() {
		$(this).parents('div.nb_element.story').removeClass('hl');
	});
	
}


function nbSendStory(article_id, nb_story_id, reply_all, comment_id) {
	
	var reply_all_flag = '';
	if (reply_all) {
		reply_all_flag = 'true';
	}
	
	if (document.browser_flag == 'non_ie') {
		$('div.nb_view').fadeOut();
		$('div.nb_reply').fadeOut();
		$('div.nb_send').fadeIn();
	} else {
		scroll(0,0);
		$('div.nb_view').hide();
		$('div.nb_reply').hide();
		$('div.nb_send').show();
	}
	$('div.nb_send iframe').attr('src', '/account/settings/news_buddies/stories/create.php?id=' + article_id + '&nb_story_id=' + nb_story_id + '&reply_all=' + reply_all_flag + '&comment_id=' + comment_id);
}

function setupBubbles() {
	
	// Make sure no other events are triggered
	$('a.account_required').unbind('click');
	
	// Bind our new code...
	$('a.account_required, a.coming_soon').click(function() {
		
		$('div.bubble.no_entry, div.bubble.coming_soon').hide();
		
		obj_wrapper = $('div#wrapper').offset();
		wrapper_top = obj_wrapper.top;
		wrapper_left = obj_wrapper.left;
		
		wrapper_padding_correction_top = 0;
		wrapper_padding_correction_left = 33;
		
		graphic_offset_top = -90;
		graphic_offset_left = -42;
		
		var obj = $(this).offset();
		var top = obj.top;
		var left = obj.left;
		
		var specific_message = '';
		
		if ($(this).hasClass('account_required')) {
			specific_message = '.no_entry';
		}
		
		if ($(this).hasClass('coming_soon')) {
			specific_message = '.coming_soon';
		}
		
		if (specific_message != '') {
			$('div.bubble' + specific_message).css('margin-top', top - wrapper_top - wrapper_padding_correction_top + graphic_offset_top + ($(this).height() / 2));
			$('div.bubble' + specific_message).css('margin-left', left - wrapper_left - wrapper_padding_correction_left + graphic_offset_left + ($(this).width() / 2));
			
			if (document.browser_flag == 'non_ie') {
				$('div.bubble' + specific_message).fadeIn();
			} else {
				$('div.bubble' + specific_message).show();
			}
			
		}
		return false;
	});
	
}



function rotate_images() {
	
	var timeout_setting = 6000;
	
	setTimeout(function(){
		rotate_images();
		$('div.news_in_pictures div.navigation a.next').click();
	},timeout_setting);
	return false;	
}


function shortNewsSetup() {

	$('div.short_news div.add_remove a.plus').click(function() {
		$(this).parents('div.short_news').find('div.news_item:hidden:first').slideDown('fast');
		return false;
	});
	
	$('div.short_news div.add_remove a.minus').click(function() {

		$(this).parents('div.short_news').find('div.news_item:visible:last').slideUp('fast');
		return false;
	});
	
}


function enableCatSorting(element_id) {
	
	element_id = '#' + element_id;

	// Define the sortable options...
	var sortable_options = {
		revert: false,										// Slow move to new position (or back)
		scroll: true,									// Don't scroll when nearing edges
		//placeholder: "ui-selected",			// class name of placeholder or drop zone
		opacity: 0.25,									// Fade back while dragging
		tolerance: 'intersect',					// Technique use to detect landing area
		forcePlaceholderSize: true,			// Forces the placeholder to have a size
		connectWith: [element_id + " .publisher_selection," + element_id +" .publishers_available"],		// Connect containers
	
		update: function(e,ui) {
		
		if ($(element_id + " .publisher_selection>li").length  > 6) {
	
			$(element_id + " .publisher_selection>li:last").replaceAll(element_id + ' .ft_triple_helper:first');
		
			// Clean up
			$(element_id + " .ft_triple_helper").remove();
	
		}},
	
		start: function(e,ui) {
			
			document.changed = true;
		
			// Our marker - where we dragged from
			$(ui.helper).after('<li style="display:none" class="ft_triple_helper"></li>');
			
			// This prevent issues caused by the box scrolling
			$('div.publishers_available_wrapper').scrollTop(0);
			
		},
	
		over: function(e,ui) {
						
			if ($(element_id + " .publisher_selection>li").length > 5) {

				// When we are dragging into the selection box only
				if($(ui.sender).hasClass('publishers_available')) {
					$(element_id + " .publisher_selection>li:last").hide();
				}
				
			}
		
		},
	
		out: function(e,ui) {
			$(element_id + " .publishers_available li").show();
		},
	
		stop: function(e,ui) {
			// Clean up
			$(element_id + " .ft_triple_helper").remove();
			$(element_id + " .publishers_available li").show();
		}
	
	};

	// Make the containers sortable
	$(element_id + " .publisher_selection").sortable(sortable_options);
	$(element_id + " .publishers_available").sortable(sortable_options);
	
	
}

function getModulePositionData() {
	
	var refs = '';
	
	// Find all the modules in the page, locate their containers...
	$('div.module.user').each(function() {
		refs += $(this).parent().attr('id') + '|' + $(this).attr('id') + ',';
	});
	
	return refs;
	
}

function close_nb_view() {
		if (document.browser_flag == 'non_ie') {
			$('div.nb_view').fadeOut();
		} else {
			$('div.nb_view').hide();
		}
	}
	
function setupOutboundLinkTargets() {
	$('a.outbound').attr('target', document.link_outbound_target);
}


function closeAllBubbles() {
	if (document.browser_flag == 'non_ie') {
		$('div.bubble').hide();
	} else {
		$('div.bubble').hide();
	}
}

function closeLanding() {
	$.fn.fancybox.close();
}

function closeAllModals() {
	$.fn.fancybox.close();
}

function newsBuddyModal(obj_ref, mode) {
		
	var width = 486;
	var height = 500;
	
	switch(mode) {
		case 'view':
			width = 486;
			height = 580;
		break;
		case 'create':
			width = 486;
			height = 560;
		break;
	}
	
	$(obj_ref).fancybox({
		'zoomSpeedIn': 0,
		'zoomSpeedOut': 0,
		'overlayShow': true,
		'overlayOpacity': 0.7,
		'overlayColor': '#000',
		'hideOnContentClick': false,
		'frameWidth': width,
		'frameHeight': height,
		'callbackOnShow': function() {
			$('#fancy_title').hide();
		}
	});
	
}




function areThereOpenModals() {
	if ($('div#fancy_content').html() != '') {
		return true;
	} else {
		return false;
	}
}
	
	
function prepareNewsBuddyModal() {
	$("#fancy_outer").height(500);
	$("#fancy_outer").css('top', parseInt($("#fancy_outer").css('top')) + 104 + 'px');
}

	