var admin = {
	linkObj				: null,
	linkLabel			: null,
    documentTitle		: document.title,
    firstLoad			: true,

	queryStringAdditions : function()
    {
		return 'app=' + applicationName
			+ '&barebones=true'
			+ '&queryStringAdditions=queryStringAdditions,app,barebones';
	}, // queryStringAdditions()

	menuClick : function(element)
    {
    	// This function is fired when the user clicks on a menu item. It will retrieve the submenu and the
        // page's content via AJAX

        var href		= admin.getQueryString($(element).attr('href'));

    	admin.loadPage(href, 'pageContent');
	}, // menuClick()

	ajaxSubmit : function(element)
    {
        // Temporary disable the submit button to prevent double submissions
        $(element).attr('disabled', 'disabled');
        setTimeout(function () { $(element).attr('disabled', ''); }, 1000);
        
        // Get the input button's parent form so we can serialize it and send it via ajax
        var ajaxForm	= $(element).parents('form');
        if (!ajaxForm)
        {
			alert('Error: this submit button\'s form element could not be found. Please make sure the submit button is located within a form element.');
        	return false;
        }
        
        // Clear out help text
        TemplatePage.submitSwitchText(ajaxForm);

        // Get the hidden callback input. We use this as a callback function throughout the submission process
        var callback	= ajaxForm.find('input:hidden[name=callback]').val();

        // Run callback function
        if (callback && eval(callback + '(1);') == false) return false;

        // Get the hidden rel input. We use this to identify the container to update with the returned content
        var updateObjId	= ajaxForm.find('input:hidden[name=rel]').val();
        if (!updateObjId)
        	updateObjId	= 'pageContent';

        var updateObj	= $('#' + updateObjId);

        // Grab any required fields that are not filled out. This will find inputs, textareas, selects, and button elements.
        // @todo make this work with radio buttons and checkboxes
        var emptyFields	= ajaxForm.find('.required :input[value=""], :input.required[value=""], .required :password[value=""], :password.required[value=""]');
        
        var unchecked	= ajaxForm.find('.required :checkbox, .required :radio').not(':checked');
        if (unchecked.length) // See if any are checked in the group
        {
        	$.each(unchecked, function() {
        		var checked	= $(this).parents('.required').find(':checkbox:checked, :radio:checked');
        		if (!checked.length)
        			emptyFields.push(this);
        	});
        }
        
        var errorObj	= ajaxForm.find('div.errors');

        if (emptyFields.length)
        {
        	// Get the text in each of the labels that point to empty required fields
        	var labels			= new Array;

            $.each(emptyFields, function() {
            	var inputId		= $(this).attr('id');
                if (inputId)
                {
            		var label	= ajaxForm.find('label[for=' + inputId + ']');
                    label		= (label.attr('title')) ? label.attr('title') : label.text();
                    if (label != '') labels.push(label.replace(/^\s+|\s+$/g, ""));
                }
            });


            // Build the error message
            var errorMessage	= '<div class="error">You must complete all of the required fields on the form, such as ';

            // Turn the labels into a sentence
            var label;
            while(labels.length)
            {
                if (labels.length == 1)
                {
                    label			= labels.shift();
                    errorMessage	+= '<strong>' + label + '</strong>.';
                }
                else if (labels.length > 2)
                {
                    label			= labels.shift();
                    errorMessage	+= '<strong>' + label + '</strong>, ';
                }
                else
                {
                    label			= labels.shift();
                    var lastLabel	= labels.shift();
                    errorMessage	+= '<strong>' + label + '</strong> and <strong>' + lastLabel + '</strong>.';
                    break;
                }
            }

            errorMessage	+= '</div>';

            if (!errorObj.length) // The errors div does not exist yet, so we need to create it
            {
            	ajaxForm.append('<div class="errors" style="display: none;"></div>');
                errorObj	= ajaxForm.find('div.errors');
            }

            // Put the error message into the errors div and slide it down so we can see it
            errorObj.html(errorMessage);
            errorObj.slideDown('fast');

            // Re-populate the help text
            TemplatePage.initSwitchText('form.ajax');

            // All done
            return false;
        }
        else // Validation was successful so we continue to submit the form
        {
        	admin.startBusy(updateObj);

            // Clean up the errors div if it is showing
            if(errorObj.length)
            	errorObj.slideUp('fast', function() { errorObj.html(''); });

            // Serialize the form data into a query string so we can send it with our ajax request
            var formFields	= ajaxForm.serialize();

            if (!admin.prompts(formFields)) {
                admin.stopBusy(updateObj);
                return false;
            }

            formFields				+= '&buttonClicked=' + encodeURI($(element).val());
        	admin.loadPage(formFields, updateObjId, ajaxForm.attr('method'));

            return true;
        } // if

	}, // ajaxSubmit()

	ajaxClick : function(element)
    {
		var href			= admin.getQueryString($(element).attr('href'));

        // Get hidden callback value. We use this as a callback function throughout the submission process
        var callback		= TemplatePage.getParameter(href, 'callback');

        // Run callback function
        if (callback && eval(callback + '(1);') == false) return false;

        var updateObjId		= $(element).attr('rel');
        if (!updateObjId)
        	updateObjId		= 'pageContent';

		var updateObj		= $('#' + updateObjId);

		if (!admin.prompts(href)) {
        	admin.stopBusy(updateObj);
        	return false;
        }

        admin.loadPage(href, updateObjId);

	}, // ajaxClick()

	prompts : function (haystack)
    {
		var prompt		= TemplatePage.getParameter(haystack, 'prompt');
		switch (prompt)
        {
        	case 'delete':
                var agree	= confirm('Are you sure you want to delete the ' + unescape(TemplatePage.getParameter(haystack, 'what')) + ' named "' + unescape(TemplatePage.getParameter(haystack, 'name')) + '"?\n\nRemember, there is no undo.');
                if (!agree) return false;
            break;

            case 'confirm':
            	var agree	= confirm('Are you sure you want to ' + unescape(TemplatePage.getParameter(haystack, 'what', 'do that').replace(/\+/g, ' ')) + '?');
                if (!agree) return false;
            break;
		}
        return true;
	}, // prompts()

	getQueryString : function(href)
    {
    	// Takes a url and returns the query string portion
        // e.g.: getQueryString('http://gustavus.edu?apples=3&oranges=5') will return 'apples=3&oranges=5'

		return href.replace(/(.*?)\?/g,'');
	}, // getQueryString()

	// DEPRECATED
    getParameter : function(haystack, needle, defaultValue)
    {
	    return TemplatePage.getParameter(haystack, needle, defaultValue);
    }, // getParameter()

	startBusy : function(busyObj)
    {
    	// Engage cues to communicate that something is happening and the user needs to wait:
        // fade out the loaded content, change the document title to "Loading...",
        // switch out the favicon for a throbber, and change the cursor to 'wait'

    	if (busyObj) $(busyObj).fadeTo(1, .5);

    	if (!$.browser.safari) // This will sorta work in Safari, but for some reason it doesn't like it very much right now
	    	document.title		= 'Loading...';

        $('head link.favicon').attr('href', '/modules/components/classes/admin/images/throbber.gif');
        $('head link.favicon').appendTo('head');

		$('body').css('cursor', 'wait');
	}, // startBusy()

	stopBusy : function(busyObj)
    {
    	// Disengage all of the cues engaged by startBusy()

    	if (busyObj) $(busyObj).fadeTo(1, 1);

    	if (!$.browser.safari)
        	document.title		= admin.documentTitle;

    	$('head link.favicon').attr('href', '/favicon.ico');
        $('head link.favicon').appendTo('head');

		$('body').css('cursor', 'default');
	}, // stopBusy()

	logout : function()
    {
    	// Remove cookies and clear out all but necessary content on the page
		// when the user logs out
        $('#pageContent').html('<p class="message">Please wait while you are being logged out. If you would like to access this area again, you must log back in.</p>');

        $('#menus').html('');
        $('#userMenu').html('');
	}, // logout(),

	loadPage : function(loc, rel, formMethod)
    {
        if (rel == 'pageContent' && formMethod != 'post') // Adds a step to the history stack
        {
        	$.historyLoad(encodeURI(loc.replace(/^.*#/, '')));
		}
		else
        {
        	admin.doHistory(loc + '&rel=' + rel + '&ajaxMethod=' + formMethod);
        } // if
	}, // loadPage()

    doHistory : function(newLocation)
    {
    	// When the hash changes, doHistory() takes care of switching
        // the content around so we don't break the back button

        var pr			= TemplatePage.getParameter(newLocation, 'pr');
        var pr2			= TemplatePage.getParameter(newLocation, 'pr2');

        if (newLocation != '' && pr == '') // inline link, don't load new content
        	return true;

        if (!admin.firstLoad && newLocation == '') // went back to the beginning of the history stack, reload the page
        {
           	window.location.reload(false);
            return true;
        } // if

        if (!admin.firstLoad || (admin.firstLoad && newLocation != ''))
        {
            if (admin.firstLoad)
                admin.firstLoad	= false;

            // Figure out what to update
            var updateObjId	= TemplatePage.getParameter(newLocation, 'rel', 'pageContent');

            admin.startBusy($('#' + updateObjId));

            var ajaxMethod		= TemplatePage.getParameter(newLocation, 'ajaxMethod', 'get');

            ajaxFunction	= (ajaxMethod == 'get') ? $.get : $.post;

            ajaxFunction(
                '/modules/components/classes/admin/ajax.php',
                newLocation + '&' + admin.queryStringAdditions(),
                function(data, textStatus) {
                    $('#' + updateObjId).html(data);
                    admin.registerEvents('#' + updateObjId);
                    admin.stopBusy($('#' + updateObjId));
                },
                'html'
            );

            // Get the sub menu
            var newSubMenu	= (pr) ? $('#' + pr + 'SubMenu') : $('#subMenus div:first');
            newSubMenu		= (newSubMenu.length) ? newSubMenu.html() : '';
            $('#subMenu').html(newSubMenu);
            if (pr2)
            {
                $('#subMenu .selected').removeClass('selected');
                $('#subMenu .' + pr2 + 'SubMenuItem').addClass('selected');
            }
            $('#subMenu a.menuAjax').click(function() { admin.menuClick(this); return false; });

            // Update main menu selection className based on pr
            $('#mainMenu li.selected').removeClass('selected');
            if (pr)
                $('#mainmenu' + pr).addClass('selected');
            else
                $('#mainMenu li:first').addClass('selected');

            return true;
		} // if
    }, // doHistory()

    registerEvents : function(container, firstLoad)
    {
    	// Attach onclick events to make sure that our ajax links and forms will work.
		if (firstLoad)
		{
			$('#pageContent form.ajax input:submit').live('click', function() {
				admin.ajaxSubmit(this);
				return false;
			});

			$('#pageContent a.ajax').live('click', function() {
				admin.ajaxClick(this);
				return false;
			});
		}
		else
        {
			if (container == null) container = '#pageContent';
	        TemplatePage.hooks(container); // Things like striped tables from template.js
		}
    } // registerEvents()

} // admin

jQuery(function(){
	$.historyInit(admin.doHistory);
	$('#mainMenu a.menuAjax').click(function() { admin.menuClick(this); return false; });
    $('#subMenu a.menuAjax').click(function() { admin.menuClick(this); return false; });
	$('#adminlogout').click(function() { admin.logout(); });
	admin.registerEvents(null, true);
});