$.fn.replace = function(o) {
	return this.after(o).remove();
};

$.fn.showItem = function(o) {
	// Is this hidden via VISIBILITY?
	if(this.css('visibility') == 'hidden') {
		return this.css('visibility','visible');
	}
	// Otherwise, it's hidden via display: none;
	return this.css('display','block');
};

$.fn.hideItem = function(o) {
	// Is this shown via VISIBILITY?
	if(this.css('visibility') == 'visible') {
		return this.css('visibility','hidden');
	}
	// Otherwise, it's shown via display: block;
	return this.css('display','none');
};


// Image preloading.
var imgs = ["/images/loading.gif","/imgs/qtag_up.gif","/images/tabnav_close.gif","/images/tabnav_close_all.gif","/images/tab_list_comb_unchecked.gif","/images/tab_list_comb_checked.gif"];
$.each(imgs, function(i, img) {
	(new Image()).src = img
});

$(document).ready(function() {
	window.CustomWidth = $('#width');

	// Make sure there is an active tab set.. if there are any tabs.
	// First, are there any tabs?
	var tabs = $('#tabs');
	var total_tabs = $('li', tabs).length;
	var active_tab = $('li.tabs-selected');

	if(total_tabs > 0) {
		// Yes. There is at least one tab.
		// Are there any selected/active tabs?
		if(active_tab.length) {
			// Yes.
		} else {
			// No. Now this is a problem. We NEED at one active tab.
			// Get the very last tab.
			var last_tab = $('li:last', tabs);
			var last_tab_id = $(last_tab).attr('id').split("_")[1];

			var last_section = $('#section_'+last_tab_id);
			$(last_tab).addClass('tabs-selected');
			$(last_section).removeClass('tabs-hide');
			$(last_section).show();
			$(last_section).css('display','block');
		}
	} // No, no tabs. Don't need to worry about checking for an active tab.

	InitializeLockTab();
	Hive.InitializeTooltips();
	Hive.InitializeBrowseHives();
	LoadEventHandlers();

	// $('#search')
	window.global_search_bar = $('#search');
	window.global_search_term = $('#search_term');
	window.global_window_width = $(CustomWidth).width();
//	window.global_window_width = $(window).width();

	// Initialize carousel
	InitializeCarousel(GetTabIndex(GetActiveTabId()));
});

// #################################################
// fix for Firefox or Interface
jQuery.iUtil.purgeEvents = function(nodeEl) {
	jQuery.iUtil.traverseDOM(
		nodeEl,
		function(el)
		{
			for(var attr in el){
				try {
					if(typeof el[attr] === 'function') {
						el[attr] = null;
					}
				} catch (e) {}
			}
		}
	);
};

// #################################################
$.fn.fastSerialize = function() {
    var a = [];

    $('input,textarea,select,button', this).each(function() {
        var n = this.name;
        var t = this.type;

        if ( !n || this.disabled || t == 'reset' ||
            (t == 'checkbox' || t == 'radio') && !this.checked ||
            (t == 'submit' || t == 'image' || t == 'button') && this.form.clicked != this ||
            this.tagName.toLowerCase() == 'select' && this.selectedIndex == -1)
            return;

        if (t == 'image' && this.form.clicked_x)
            return a.push(
                {name: n+'_x', value: this.form.clicked_x},
                {name: n+'_y', value: this.form.clicked_y}
            );

        if (t == 'select-multiple') {
            $('option:selected', this).each( function() {
                a.push({name: n, value: this.value});
            });
            return;
        }

        a.push({name: n, value: this.value});
    });

    return a;
};

// #################################################
function addQuickTagEvents() {
	var quicktags = $('#quicktags');
	if (!quicktags.length) return;
	
	var origHeight = quicktags.height();
	
	$('dt:first', quicktags).toggle(function() {
		quicktags
			.addClass('quicktags-open')
			.animate({height: quicktags.get(0).scrollHeight}, "normal");
	}, function() {
		quicktags
			.removeClass('quicktags-open')
			.animate({height: origHeight}, "normal");
	});

	function quickTagOnClick() {
		if (!this.href) {
			var search = $('#search_term');
			
			// replace any existing quicktag in the search bar
			var oldval = search.val();
			var findquicktag = oldval.indexOf(';;');
			if (findquicktag != -1)
				oldval = oldval.substr(0, findquicktag);
			
			search.val(oldval + ';;' + this.innerHTML);
			SearchSubmit();
			return false;
		}
	}

	$(document).ready(function() {
		if(open_result_links_new_window) {
			$('#quicktags dl a').attr('target','_blank');
		}
	});

	$('#quicktags dl a').click(quickTagOnClick);

	$('#quicktag-form').submit(function() {
		var form = this;
		if (form.shortcutfeature.checked) {
			var a = document.createElement('a');
			a.innerHTML = form.shortcutname.value;
			if (form.shortcutcommand.value.indexOf('http://') == 0 || form.shortcutcommand.value.indexOf('https://') == 0) {
				a.href = form.shortcutcommand.value;
			} else {
				$(a).click(quickTagOnClick);
			}

			// Iterate through top-section quicktags.. to get the highest ID #. Add 1 to it to get the next id.
			var next_id = 0;
			$('#quicktags_dl dd').each(function(i) {
				// ie: quicktag_link_0
				next_id++;
			});
			
			var dd = document.createElement('dd');
			dd.appendChild(a);
			$(dd).attr({id: "quicktag_link_"+next_id});
			$('#quicktags dl').append(dd);
			
			// in case there is a new line of quicktags, expand
			quicktags.animate({height: quicktags.get(0).scrollHeight}, "normal");
		}
		$.get("ajax/add_quicktag.php", {
			shortcutfeature: form.shortcutfeature.checked ? 1 : 0,
			shortcutname: form.shortcutname.value,
			shortcutcommand: form.shortcutcommand.value
		}, function() {

			var new_key = parseInt($('#next_key').val());
			$('#next_key').val(parseInt(new_key)+1);

			var parameters = {
				shortcutfeature: form.shortcutfeature.checked ? 1 : 0,
				shortcutname: form.shortcutname.value,
				shortcutcommand: form.shortcutcommand.value,
				cur_key: new_key
			}; // object containing the parameters sent to /ajax/add_quicktag.php

			$.get("/ajax/add_settings_quicktag.php", parameters, function(html) {
				if($('#quicktags_table')) {
					$('#quicktags_table').html(html);
					Hive.addDropDowns();
					SetupQuicktagsSorting();
				}
			});

			$(form).find('input:text').val(''); // blank out the add quicktag fields.

		});
		return false;
	});
}

$(function() {
	// open all links with rel="new-window" in a new window
	$("a[@rel='new-window']").click(function(){
		window.open(this.href);
		return false;
	});

	// delete any 'tab' with class no-tabs (just there for validation
	$('#tabs li.no-tabs').remove();

	// add the invalid name attribute to maps to fix them in Firefox
	$('map').each(function(){
		if (!this.name)	this.name = this.id;
	});

//	$('#container').tabs({ });
	$('#container').tabs();
//	$.tabs("container");

	// Only enable sortable tabs if they have them enabled in the settings panel.
	if(enable_drag_drop_tabs == 1) {
		// setup tab sorting
		$('#tabs').Sortable({
			'accept':		'tabitem',
			'helperclass':	'tab-drag-helper',
			'opacity':		0.7,
			'fit':			false,
			'floats':		true,
			'tolerance':	'intersect',
			'axis':			'horizontally',
			'revert':		true,
			'onStart':		function() {
								$('ul.tab-list').remove();
			},
			'onStop':		function() {
								// should be done automatically but sometimes isn't
								$('#sortHelper').hide();
								
								$.get('ajax/tab_order.php?' + $.SortSerialize('tabs').hash);

								$('a', this).click();
							}
		});
	}

	$('#container').css('visibility','visible');

	// if the settings page is there we need to enable quicktag sorting
	SetupQuicktagsSorting();

	// See if an active tab is supposed to be set. If so, set it.
	if(starting_active_tab) {
		SetActiveTab(starting_active_tab);
	}

	// Load the event handlers.
	LoadEventHandlers();

	// #################################################
	// CLICK HANDLER FOR SAVED SEARCHES - Mike
	InitializeSavedSearch();
	$('#savedsearch_open').click(function() {
		SaveSearch();
	});

	// TwerqIt image map handler
	$('#twerqit_check').toggle(function(){
		$('#twerqit').attr('src', '/images/twerqit_unchecked.gif');
		document.getElementById('create_new_tab').checked = false;
	}, function() {
		$('#twerqit').attr('src', '/images/twerqit_checked.gif');
		document.getElementById('create_new_tab').checked = true;
	});
	$('#twerqit_submit').click( function() { $('#search_form').submit(); } );
	
	// qtriggers
	$('#qtriggers_button').unbind('click').click(function(){
		var qtriggers = $('#qtriggers');

		if(qtriggers.css('display') != 'block') {
			$('#qtriggers_button').attr('src','/imgs/qtrigger_up.gif');
			$('#qtriggers').show();
		} else {
			$('#qtriggers_button').attr('src','/imgs/qtrigger_down.gif');
			$('#qtriggers').hide();
		}

		InitializeQTriggers();
	});

	$('#qtriggers a').click(function() {
		var search = $('#search_term');
		var search_text = search.val();

		if(this.rel == 'before') {
			if(qtrigger_mode == 2) { // beginner mode.
				search_text = $('div.qtrigger_beginner_link',this).html() + search_text;
			} else {
				// advanced mode.
				// To do combo triggers, it must be "BEFORE", and it must be ADVANCED mode. This is the only block that fits the criteria.
				// Do we already have a ":" in our search phrase?
				var trigger = $(this).html();
				var index_colon = search_text.indexOf(':');
				if(index_colon > -1) {
					// A ":" already exists. We need to take our trigger, strip off the colon, and add it BEFORE anything.
					var trigger_index_colon = trigger.indexOf(':');
					if(trigger_index_colon > -1) {
						trigger = trigger.substring(0,trigger_index_colon);
					}
				}
				search_text = trigger + search_text;
			}
		} else {
			if(qtrigger_mode == 2) { // beginner mode
				search_text += $('div.qtrigger_beginner_link',this).html();
			} else {
				// advanced mode.
				// <a title="Edit Tab" rel="before" style="float: left;">e:</a>
				search_text += $(this).html();
			}
		}

		search.val(search_text);
		search.get(0).focus();

		if(qtrigger_mode == 2) { // beginner.
			$('#qtriggers').hide();
			$('#qtriggers_button').attr('src','/imgs/qtrigger_down.gif');
		}
	});

	SetTipLinks();

	addQuickTagEvents();

	//########################################################
	// Shortlist Drop-down
	$('#shortlist_open').unbind('click').click(function() {
		var shortlist = $('#shortlist_list');
		var search = $('#search');
		
		if (shortlist.length) {
			shortlist.remove();
			return false;
		}

		$.getJSON('ajax/shortlist_select.php', '', function(data) { // data = array
			//shortlist.remove();

			if (!data.length) {
				shortlist = $('<div id="shortlist_list">No shortlisted items</div>');
			} else {
				shortlist = $('<select id="shortlist_list" size="'
					+ Math.min(6, data.length + 2) + '"></select>');

				// #################################################
				shortlist.unbind('click').click(function() {
					var option = this.options[this.selectedIndex];
					shortlist.hide();

					// See if this shortlist tab already exists.
					var this_shortlist = '**'+$(option).val();
					var check_tab = $('#tabs li[@title="'+this_shortlist+'"]');
					if(check_tab) {
						if($(check_tab).html()) {
							// It already exists. Switch to it.
							SetActiveTab( $(check_tab).attr('id').split('_')[1]);
							return;
						}
					}

					search.find('input:text').val('**' + option.value);
					SearchSubmit();
				});
				// #################################################

				$.each(data, function(i, term) {
					shortlist.append('<option value="' + term + '">' + term + '</option>');
				});
				shortlist.append('<option value="Combined Shortlist">Combined Shortlist</option>');
				shortlist.append('<option value="Open All Shortlists">Open All Shortlists</option>');
			}
			$(document.body).append(shortlist);
			var search_pos = findPos(search.get(0));
			shortlist.css({
				width:	search.width() + 'px',
				top:	(search_pos.y + search.height()) + 'px',
				left:	search_pos.x + 'px'
			});
			
			if(shortlist.length) {
				$(document.body).one('click', function(){
					if($('#shortlist_list').length) {
						shortlist.remove();
					}
				});
			}
			
			shortlist.show();
			shortlist.focus();
		});

		return false;
	});

//	$('#search_form').submit(function(){setTimeout(ResizeHandler, 2000);});

});

// #################################################
// #################################################
// #################################################
// #################################################
// #################################################

$(document).ready(function() {
	$(window).unbind('resize').resize(function() {
		//ResizeHandler();
		StartResize();
	});

	ResizeHandler();
});

// #################################################
function StartResize() {
	if(window.start_timer) {
		clearTimeout(window.start_timer);
		window.start_timer = null;
	}
	window.start_timer = setTimeout(WindowResized, 500);
//	WindowResized();
//	ResizeHandler();
}

// 	#################################################
function WindowResized() {
	// Check previous width.. with the new width. Make sure they are different.
	var current_width = $('body').width();
	if(current_width != window.window_width) {
		ResizeHandler();
		window.window_width = current_width;
	}
}

// #################################################
function ResizeHandler() {
	ShrinkTabs(); return;
}


// #################################################
function CalculateWidths() {
	var retval = {};
	/* Need widths for:
	#logo
	#menu
	#twerqit

	and total of those 3.
	*/

	retval.logo = $('#logo').width();
	retval.menu = $('#menu').width();
	retval.twerqit = $('#twerqit').width();

	retval.total = retval.logo + retval.menu + retval.twerqit;
	retval.body = $(CustomWidth).width();

	retval.search_term = $('#search_term').width();
	retval.search = $('#search').width();

	return retval;
}

// #################################################
function UpdateTotalSearches() {
	$.ajax({
		type:		"GET",
		url:		"/ajax/get_total_searches.php",
		dataType:	"html",
		success:	function(data) {
						$('#total_searches').html(data);
					}
	});
}


// For open result links in new window...
$(document).ready(function() {
	if(open_result_links_new_window == true) {
		$('a.search_title').attr("target", "_blank");
	} else {
		$('a.search_title').attr("target", "");
	}

	var current_active_tab = GetActiveTabId();
	// Is this tab an active hive tab?
	var hive_tabs = $('#hive_tabs_'+current_active_tab);
	if( hive_tabs.length ) {
		// Yes.
		$('#tab_'+current_active_tab).addClass('hive-tabs-selected');
	}
});