
	var menu_data;
	var menu_options;
	var tab_counter = 0;
	var dialog_table = null;
	var ajaxOptions = { beforeSubmit: beforeAjaxSubmit, success: afterAjaxSubmit, dataType: 'json' };
	var tab_template = '<li><a href="#{href}" class="tab_title">#{label}</a></li>';
	var tab_template_close = '<li><a href="#{href}" class="tab_title">#{label}</a> <span class="ui-icon ui-icon-close">Close Tab</span></li>';
	var loading_spinner = '<div class="loading">Loading Data...</div>';

	// Called before submitting ajax form
	function beforeAjaxSubmit(formData, jqForm, options) {
		$.clearErrors();
		if (!$('#' + $(jqForm).attr('id')).validate().form()) {
			return false;
		} else {
			return true;
		}
	}

	// Called after submitting ajax form
	function afterAjaxSubmit(data) {
		var callback, message, message_class, message_icon;

		if (data.callback) {
			callback = data.callback;
			eval('$(this).' + callback + '(data)');
		} else if (data.success || data.error) {
			$.callbackMessage(data);
		}
	}

	function newTab(path, title) {
		tab_counter++;
		var selected;
		path = path.replace('http://', '').replace('staging.', '').replace('www.', '').replace('network.', '').replace('bluetopmedia.com', '').replace('bluetop.sanisoft.com', ''); // needed for IE
		//var tab = '#' + path.toLowerCase().substr(1, path.length).replace(/\//g, '_') + '-' + tab_counter;
                var tab = '#' + path.toLowerCase().substr(1, path.length).replace(/\//g, '_').replace(':', '_').replace(':', '_');

                // First check if the tab already exists. If it exists then make that tab active
                // This way we will have a single tab for a section and no duplicate tabs can be opened
                if ($(tab).length) {
                    // The tab exists so make it active and return without doing anything else
                    $('#content_tabs').tabs('select', tab);
                    return;
                }

		// First we create an empty tab.
		$('#content_tabs').tabs('add', tab, title, tab_counter);
		
		// Set the loading spinner.
		$(tab).html(loading_spinner);

		// Then we switch to the new tab which should be showing the loading spinner by now.
		$('#content_tabs').tabs('select', tab);

		// Now that the tab is focused, we start loading the data.
		$.get(path, function(data){
			$(tab).slideUp(1, function() {
				$(tab).hide().html(data).slideDown(1);
                    // Init the click event of all .button elements
                    $.initButtonClick();
                    $.initDataTable(tab);
                    $.initPageLinks(tab);
                    showDialogBox();
                    //showSearchBox(tab);
			});
		});
	}

    /**
    * Function to show the dialog box
    */
	var showDialogBox = function() {			
            // Unbind the click event from ajax dialog links first
            $('a[rel*=ajax-dialog], input[lang*=ajax-dialog]').unbind('click');
			// setup ajax dialog boxes.
			$('a[rel*=ajax-dialog], input[lang*=ajax-dialog]').click( function() {
				var d = '#dialog';
				var url = ($(this).attr('lang') == 'ajax-dialog') ? $(this).attr('id') : $(this).attr('href'); //get url from href, or id if button.
				$(d).empty().html(loading_spinner).dialog({ title: $(this).attr('title'), close: function() { keyPressEvent(btOptions, btContainer); }}).dialog('open');
				$(document).unbind("keydown");
				$.get(url, function(data) {
					$(d).empty().html(data);
					$('input[name*=ajax-close-dialog]').unbind("click");
					$('input[name*=ajax-close-dialog]').click( function() {
						dialog_table = null;
						$('#dialog').dialog('destroy');
						keyPressEvent(btOptions, btContainer);
						showDialogBox();
					});
				});
				return false;
			});

			// close button
			$('input[name*=ajax-close-dialog]').click( function() {
				dialog_table = null;
				$('#dialog').dialog('destroy');
				keyPressEvent(btOptions, btContainer);
			});
	}

	$(function() {
		$.ui.dialog.defaults.autoOpen = false;
		$.ui.dialog.defaults.modal = true;
		$.ui.dialog.defaults.bgiframe = true;
		$.ui.dialog.defaults.width = 700;
		$.ui.dialog.defaults.minWidth = 700;
		$.ui.dialog.defaults.minHeight = 150;
		$.ui.dialog.defaults.title = '';
		$.ui.dialog.defaults.position = ['center', 175];

		$.callbackMessage = function(data) {
			if (data.error) {
				message = data.error;
				message_class = 'ui-state-error';
				message_icon = 'ui-icon-alert';
			} else if (data.message) {
				message = data.message;
				message_class = 'ui-state-highlight';
				message_icon = 'ui-icon-info';
			}
			if (message) {
				$('.messages').empty().append(
					'<div class="ui-widget">' +
					'<div class="' + message_class + ' ui-corner-all">' +
					'<p><span class="ui-icon ' + message_icon + '"></span>' + message + '</p>' +
					'</div></div>'
				).slideDown(200, function() {
					setTimeout('if ($(\'.messages\').is(\':visible\')) { $(\'.messages\').slideUp(200); }', 5000);
				});
			}
			return;
		}

		$.clearErrors = function() {
			if ($('.messages').is(':visible')) {
				$('.messages').slideUp(1, function() {
					$(this).empty();
				});
			}
			return;
		}

		$.setBrowseMenu = function(data) {
			menu_data = data;
			$('#browse_menu').menu({
				content: menu_data,
				backLink: false,
				showSpeed: 1,
				width: 180,
				maxHeight: 300
			});
		}

		$.clearSelection = function() {
			// deselect any selected / highlighted text.
			// useful when double clicking within application.
			var sel;
			if (document.selection && document.selection.empty) {
				document.selection.empty();
			} else if (window.getSelection) {
				sel = window.getSelection();
				if(sel && sel.removeAllRanges) {
					sel.removeAllRanges();
				}
			}
		}

		$.getTabIndex = function(s) {
			var tab_index = -1;
			$('#content_tabs').find('.tab_title').each(function (i) {
				if ($(this).text().toLowerCase().indexOf(s) > -1) { tab_index = i;	}
			});
			return tab_index;
		}

        $.getTabContainerId = function(s) {
			var href = '';
			$('#content_tabs').find('.tab_title').each(function (i) {
				if ($(this).text().toLowerCase().indexOf(s) > -1) { href = $(this).attr("href");	}
			});
			return href;
		}

		$.logout = function() {
			$.callbackMessage({message: 'Please wait while you\'re logged out...'});
			$.get('/logout', function(data) {
				// Kill menu and sidebar.
				$('#browse_menu').menu({ killMenu: true });
				$('.set_menu').empty();
				$('#sidebar').hide();

				// Remove all open tabs.
				for (var i = $('#content_tabs').tabs('length') - 1; i >= 0; i--) {
					$('#content_tabs').tabs('remove', i);
				}

				// Set tab to not have a close button
				$('#content_tabs').tabs('option', 'tabTemplate', tab_template);

				// open dashboard tab.
				newTab('/dashboard', 'Member Login');

				if ($("#info").length >= 1) {
					$("#info").html("");
				}
				// Reset tab template back to having a close button.
				$('#content_tabs').tabs('option', 'tabTemplate', tab_template_close);
				$.callbackMessage({message: 'You have been successfully logged out.'});
			});
		}

		$.initDialogBox = function(x) {
			// Check for passed height to display dialog box at.
			if (x) {
				$('#dialog').dialog('option', 'position', ['center', x]);
			}

			$(document).unbind("keydown");
            // Unbind the click event from ajax dialog links first
            $('a[rel*=ajax-dialog], input[lang*=ajax-dialog]').unbind('click');
			// setup ajax dialog boxes.
			$('a[rel*=ajax-dialog], input[lang*=ajax-dialog]').click( function() {
				var d = '#dialog';
				var url = ($(this).attr('lang') == 'ajax-dialog') ? $(this).attr('id') : $(this).attr('href'); //get url from href, or id if button.
				$(d).empty().html(loading_spinner).dialog({ title: $(this).attr('title')}).dialog('open');
				$.get(url, function(data) {
					$(d).empty().html(data);
				});
				return false;
			});

			// close button
			$('input[name*=ajax-close-dialog]').unbind("click");
			$('input[name*=ajax-close-dialog]').click( function() {
			    // Adding code to bind event to menus
				//$.setBrowseMenu($('#browse_menu').next().html());
				dialog_table = null;
				$('#dialog').dialog('destroy');
			});
		}

		$.initDataTable = function(tabId) {
			/* Data Table properties */
			//get id of currently selected tab so that we can attach the .data-table properties to each page individually.
			

			
			if (typeof(tabId) != "undefined") {
				var id = tabId + ' ';
			} else {
				var id = (dialog_table != null) ? (dialog_table + ' ') : ($('#content_tabs').find('li.ui-tabs-selected a').attr('href') + ' ');
			}

			$('.data-table tr.data-table-tr-selectable:even td').css("background-color", "#f0f0f0");

			$(id + '.data-table-tr-selectable').unbind("click");
			$(id + '.data-table-tr-selectable').click( function() {
				var row_id = ($(this).attr('id')) ? $(this).attr('id') : null;
				var subrow = ((row_id) && ($('#' + row_id + '_subrow').html())) ? $('#' + row_id + '_subrow') : null;
				if($(this).attr('class').indexOf('data-table-tr-selected') > -1) {
					$(this).removeClass('data-table-tr-selected');
					$(this).addClass('data-table-tr-hover');
					if (subrow) { subrow.hide(); }
					return false;
				}
				$(id + '.data-table-tr-selectable').removeClass('data-table-tr-selected');
				$(id + '.data-table-tr-subrow').hide();
				$(this).removeClass('data-table-tr-hover');
				$(this).addClass('data-table-tr-selected');
				if (subrow) { subrow.show(); }
				$.clearSelection();
				
			});

			$('.data-table tr').hover(
				function () {
					var tr = $(this).attr('class');
					if (tr.indexOf('data-table-tr-selected') == -1 && tr.indexOf('data-table-tr-nohover') == -1 && tr.indexOf('data-table-tr-subrow') == -1) {
						$(this).addClass('data-table-tr-hover');
					}
				},
				function () {
					$(this).removeClass('data-table-tr-hover');
				}
			);

			$('input[class*="copy-url"]').unbind("click");
			$('input[class*="copy-url"]').click( function() {
				document.getElementById($(this).attr('id')).select();
			});
		
		}

		$.initPageLinks = function(tabId) {
			//get id of currently selected tab so that we can attach the link properties to each page individually.
			if (typeof(tabId) != "undefined") {
				var id = tabId + ' ';
			} else {
				var id = $('#content_tabs').find('li.ui-tabs-selected a').attr('href') + ' ';
			}

			$(id + '.blink').unbind("click");
			$(id + '.blink').click(function() {

				//var tab = $('#content_tabs').tabs('option', 'selected'); // probably isnt needed.
				var url = $(this).attr('href');

				//Load the data via ajax request
				$(id).empty().html(loading_spinner);
				$(id).load(url, {}, function() {
					$.initDataTable();
                    $.initPageLinks();
                    showDialogBox();
				});
				return false;
			});

			$(id + '.new-tab').unbind("click");
			$(id + '.new-tab').click( function() {
				newTab($(this).attr('href'), $(this).attr('title'));
				return false;
			});
		}

		$.initPageEvents = function() {
		    // Call the functions only if request is not an ajax request
			//if ((typeof(isAjaxRequest) != "undefined") && (isAjaxRequest == false)) {
				$.initDialogBox();
				$.initDataTable();
				$.initPageLinks();
				$.initButtonClick();
			//}
		}

		$.countryChange = function(cid, sid) {
			if($('#provinceBox').is(':visible')) {
				$('#provinceBox').fadeOut(1);
			}
			if ((sid) && (sid > 0)) {
				// pass in the state/province id as well.
				cid = cid + '/' + sid
			}
			$('#provinceBox').load('/users/getStates/' + cid, function() { $('#provinceBox').fadeIn(1); });
			return false;
		}

		$.initButton = function() {
			if ($(this).attr('lang') != 'ajax-dialog') { //ignore buttons that open dialog boxes.
				if ($(this).attr('lang') && $(this).attr('title')) {
					newTab($(this).attr('lang'), $(this).attr('title'));
				}
			}
			return false;
		}

		$.initButtonClick = function () {
			// First unbind previous initButton click handler
			$('.button').unbind('click', $.initButton);
			// Button & Click handlers
			$('.button').click($.initButton).hover(function() {
				$(this).addClass("ui-state-hover");
			}, function() {
				$(this).removeClass("ui-state-hover");
			});
			$('.options a[title]').tipsy({gravity: 's'});
		}

		// Left Side Bar Tabs
		var $sidebar_tabs = $('#sidebar_tabs').tabs({cache: false});
		//var $sidebar_tabs = $('#sidebar_tabs').tabs({cache: false, disabled : [1]}); // with disabled search tab.

		/*
		$('#sidebar_tabs').bind('tabsselect', function(event, ui) {
			var selected = $('#sidebar_tabs').tabs('option', 'selected');

			switch (selected) {
				case 0: //$('#browse_menu').menu({ killMenu: true });
						$('.fg-menu-container').hide();
						$('#search').show();
						break;

				case 1: $('#search').hide();
						$('.fg-menu-container').show();
						//$('#browse_menu').menu({
							//content: menu_data,
						//	backLink: false,
						//	showSpeed: 1,
						//	width: 180,
						//	maxHeight: 200
						//});
						break;
			}
		});
		*/

		// Main Content Tabs
		var $content_tabs = $('#content_tabs').tabs({
			cache: false,
			collapsible: false,
			tabTemplate: tab_template_close,
			idPrefix: 'ui-tabs',
			ajaxOptions: { cache: false },
			add: function(event, ui) {
				$(ui.panel).append('<div class="loading">Loading Data...</div>');
			}
		});

		// remove the tab on click
		$('#content_tabs span.ui-icon-close').live('click', function() {
			var index = $('li', $content_tabs).index($(this).parent());
			$('#content_tabs').tabs('remove', index);
		});

		// Added this code to attach address plugin
		/*$.address.change(function(event) {
		    var path = event.value.replace('/', '');
			if (path != '') {
		    	var tabIndex = $.getTabIndex(path);
		    	$('#content_tabs').tabs('option', 'selected', tabIndex);
			}
		});*/

		// Added this code to show the search box on tab click
		//$('#content_tabs').bind('tabsselect', function(event, ui) {
			//tabId = '#' + $(ui.panel).attr("id");
			//showSearchBox(tabId);

            // Added this code to set the value for the address plugin
            /*if ($(ui.tab).text() != '') {
				$.address.value($(ui.tab).text().toLowerCase());
			}*/
		//});

		$.updateTitle = function(t) {
			document.title = 'Blue Top Media : ' + t;
		}

	});

