// If DOM ready
$(function() {
    
    /*
     * Variables
     */
    var autoSubmitTimeout;
    var autoSubmitForm;
    var warningWindow;
    var sessionLength = 1440000;
    var warningLength = 120000;
    
    /*
     * Session timeout warning
     */
    function preSessionTimeout()
    {
    	
    	// Update length of session left
    	sessionLength = sessionLength - (sessionLength - warningLength);
    	
    	// Open timeout warning window
    	warningWindow = window.open('', 'wBox', 'height=200,width=400');
    	warningWindow.document.write('<html>');
    	warningWindow.document.write('<head>');
    	warningWindow.document.write('<style type="text/css">');
    	warningWindow.document.write('body { font-family: Arial; }');
    	warningWindow.document.write('</style>');
    	warningWindow.document.write('</head>');
    	warningWindow.document.write('<body>');
    	warningWindow.document.write('<div id="message">');
    	warningWindow.document.write('<h1>Warning!</h1>');
    	warningWindow.document.write('<p>');
    	warningWindow.document.write('Your session will expire in ');
    	warningWindow.document.write('<span id="seconds">');
    	warningWindow.document.write(sessionLength / 1000);
    	warningWindow.document.write('</span>');
    	warningWindow.document.write(' seconds.');
    	warningWindow.document.write('</p>');
    	warningWindow.document.write('<p>');
    	warningWindow.document.write('Please save your work now ');
    	warningWindow.document.write('or you will be logged out.');
    	warningWindow.document.write('</p>');
    	warningWindow.document.write('<p>');
    	warningWindow.document.write('<a href="#" onClick="self.close();">');
    	warningWindow.document.write('[x] Close');
    	warningWindow.document.write('</a>');
    	warningWindow.document.write('</p>');
    	warningWindow.document.write('</div>');
    	warningWindow.document.write('</body>');
    	warningWindow.document.write('</html>');
    	warningWindow.document.close();
    	
    	// Enable timeout countdown
    	setTimeout(sessionTimeoutCountdown, 1000);
    	
    }
    
    // Enable session timeout warning
    setTimeout(preSessionTimeout, sessionLength - warningLength);
    
    /*
     * Session timeout countdown
     */
    function sessionTimeoutCountdown()
    {
    	
    	// Count down session length
    	sessionLength = sessionLength - 1000;
    	
    	// Check if length not zero
    	if (sessionLength > 0) {
    		
    		// Get number of seconds left
    		var secondsLeft = sessionLength / 1000;
    		
    		// Update number of seconds until timeout
        	warningWindow.document.getElementById('seconds').innerHTML = secondsLeft;
        	
    		// Set timeout for next countdown
    		setTimeout(sessionTimeoutCountdown, 1000);
    	
    	} else {
    		
    		// Build msg
    		var msg = '<h1>Warning!</h1>';
    	    msg += '<p>You have been logged out for security purposes.</p>';
    	    msg += '<p>Any unsaved work may have been lost.</p>';
    	    msg += '<p><a href="#" onClick="self.close();">[x] Close</a></p>';
    		
    		// Update warning to say session has expired
    		warningWindow.document.getElementById('message').innerHTML = msg;
    		
    	}
    	
    }
    
    /*
     * Setup auto-focus field
     */
    $('.autoFocus').focus();
    
    /*
     * Setup auto hide/show
     */
    $('.autoHide').css('display', 'none');
    $('.autoShow').css('visibility', 'visible');
    
    /*
     * Setup auto-submit forms
     */
    
    // Hide submit button
    $(".autoSubmit input[type='submit']").css('display', 'none');

    // On input change
    $(".autoSubmit input").keyup(function()
    {
        
        // Check if timeout already set
        if (autoSubmitTimeout !== undefined) {
            
            // Clear timeout
            clearTimeout(autoSubmitTimeout);
            
        }
        
        // Save auto submit form id
        autoSubmitForm = $(this).parents('form').attr('id');
        
        // Set new timeout
        autoSubmitTimeout = setTimeout(function() {
            
            // Check if timeout still defined
            if (autoSubmitTimeout !== undefined) {
                
                // Clear timeout
                clearTimeout(autoSubmitTimeout);
                autoSubmitTimeout = undefined;
                
                // Check if form defined
                if (autoSubmitForm !== '') {
                    
                    // Submit by id
                    $('#' + autoSubmitForm).submit();
                    
                } else {
                    
                    // Submit by class
                    $('.autoSubmit').submit();
                    
                }
                
            }
            
        }, 500);
        
    });

    // On radio change
    $(".autoSubmit input:radio").change(function()
    {

        // Check if timeout already set
        if (autoSubmitTimeout == undefined) {

            // Get submit url
            var submitUrl = $(this).parents('form').attr('action')
        	
            // Update results
            doPage(submitUrl);

        }
        
    });
    
    // On select chnage
    $(".autoSubmit select").change(function()
    {
        
        // Check if timeout already set
        if (autoSubmitTimeout == undefined) {

            // Get submit url
            var submitUrl = $(this).parents('form').attr('action')
        	
            // Update results
            doPage(submitUrl);

        }
        
    });
    
    // Disable submit by default
    $(".autoSubmit").submit(function() { return false; });
    
    /*
     * Setup search forms
     */
    
    // Add submit event handler
    $('form.search').submit(function()
    {
        
        // Get form url
        var formUrl = $(this).attr('action');

        // Reset page cookie
        $.cookie(cookieKey + '[page]', '1', { path: '/' });
        
        // Do search
        doSearch(formUrl);
        
    });
    
    // Add letter event handler
    $('form.search a.letter').click(function()
    {
        
        // Get letter url
        var letterUrl = $(this).attr('href');

        // Set all letters to normal font weight
        $('form.search .letter').css('font-weight', 'normal');
        
        // Set selected letter to bold
        $(this).css('font-weight', 'bold');
        
        // Reset page cookie
        $.cookie(cookieKey + '[page]', '1', { path: '/' });
        
        // Do letter search
        doLetter(letterUrl);
        
        // Disable link
        return false;
        
    });

    // Navigate page function
    function navPage(e)
    {
        
        // Update results
        doPage($(e).attr('href'));
        
    }
    
    // Bind search results navigation link event handlers
    function bindResultsLinks()
    {
        
        // Set search results navigation link event handlers
        $('#searchResultsNavigation a').click(function(e) {
            
            // Nav page
            navPage($(this));
            
            // Disable link
            return false;
            
        });
        
    }
    
    // Add event handlers for search results navigation
    bindResultsLinks();
    
    // Do search
    function doSearch(searchUrl)
    {
    	
        // Check if timeout already set
        if (autoSubmitTimeout !== undefined) {
            
            // Clear timeout
            clearTimeout(autoSubmitTimeout);
            
        }
        
        // Append ajax to search url
        searchUrl = searchUrl + '/ajax';
        
        // Get search value
        var searchValue = $('#search').val();
        
        // Check if filter element exists
        if ($('#filter').attr('id')) {
        	
        	// Get filter value
        	var filterValue = $('#filter').val();
        	
        } else {
        	
        	// Set filter value to empty
        	var filterValue = '';
        	
        }

        // Check if show element exists
        if ($('#show').attr('id')) {
        
        	// Get show value
        	var showValue = $('input:radio:checked[name=show]').val();
        	
        } else {
        	
        	// Set show value to empty
        	var showValue = '';
        	
        }
        
        // Check if search value entered and at least 3 chars long or filter specified
        if ((searchValue != '' && searchValue.length > 2) || filterValue != '') {
            
            // Save search, filter and show cookies
            $.cookie(cookieKey + '[search]', searchValue, { path: '/' });
            $.cookie(cookieKey + '[filter]', filterValue, { path: '/' });
            $.cookie(cookieKey + '[show]', showValue, { path: '/' });
            
            // Check if search not blank
            if (searchValue != '') {
            	
            	// Clear letter cookie
            	$.cookie(cookieKey + '[letter]', '', { path: '/' });
            	
            }
            
            // Set page cookie to 1
            $.cookie(cookieKey + '[page]', '1', { path: '/' });
            
            // Create new ajax request
            $.ajax({
                
                type: "POST",
                url: searchUrl,
                data: 'search=' + searchValue + '&filter=' + filterValue + '&show=' + showValue,
                
                beforeSend: function() {
                    
                    // Show loading icon
                    $('#searchResults').addClass('resultsLoading');
                    
                },
                
                complete: function() {

                    // Hide loading icon
                    $('#searchResults').removeClass('resultsLoading');
                    
                },
                
                success: function(resultHtml) {
                    
                    // Show result
                    $('#searchResults').html(resultHtml);

                    // Bind result links
                    bindResultsLinks();
                    
                }
                
            });
            
        }
        
        // Disable submit
        return false;
        
    };
    
    // Do letter
    function doLetter(letterUrl)
    {
        
        // Get letter url length
        var urlLen = letterUrl.length;
        
        // Get letter
        var letter = letterUrl.substring(urlLen - 1, urlLen);

        // Append ajax to letter url
        letterUrl = letterUrl + '/ajax';
        
        // Save letter cookie and clear search cookie
        $.cookie(cookieKey + '[search]', '', { path: '/' });
        $.cookie(cookieKey + '[letter]', letter, { path: '/' });
        
        // Clear search
        $('#search').val('');
        
        // Create new ajax request
        $.ajax({
            
            type: "POST",
            url: letterUrl,
            data: '',
            
            beforeSend: function() {
                
                // Show loading icon
                $('#searchResults').addClass('resultsLoading');
                
            },
            
            complete: function() {

                // Hide loading icon
                $('#searchResults').removeClass('resultsLoading');

            },
            
            success: function(resultHtml) {
                
                // Show result
                $('#searchResults').html(resultHtml);

                // Bind result links
                bindResultsLinks();
                
            }
            
        });
        
    }

    // Do page
    function doPage(pageUrl)
    {
        
        // Get page url length
        var urlLen = pageUrl.length;
        
        // Get last slash position
        var lastSlash = pageUrl.lastIndexOf('/');
        
        // Get page
        var page = pageUrl.substring(lastSlash + 1, urlLen) - 0;
        page = (page > 1) ? page : 1;
        
        // Save page cookie
        $.cookie(cookieKey + '[page]', page, { path: '/' });

        // Append ajax to page url
        pageUrl = pageUrl + '/ajax';

        // Check if filter element exists
        if ($('#filter').attr('id')) {
        	
        	// Get filter value
        	var filterValue = $('#filter').val();
        	
        } else {
        	
        	// Set filter value to empty
        	var filterValue = '';
        	
        }

        // Check if show element exists
        if ($('#show').attr('id')) {
        
        	// Get show value
        	var showValue = $('input:radio:checked[name=show]').val();
        	
        } else {
        	
        	// Set show value to empty
        	var showValue = '';
        	
        }
        
        // Save filter and show cookies
        $.cookie(cookieKey + '[filter]', filterValue, { path: '/' });
        $.cookie(cookieKey + '[show]', showValue, { path: '/' });
        
        // Create new ajax request
        $.ajax({
            
            type: "POST",
            url: pageUrl,
            data: '',
            
            beforeSend: function() {
                
                // Show loading icon
                $('#searchResults').addClass('resultsLoading');
                
            },
            
            complete: function() {

                // Hide loading icon
                $('#searchResults').removeClass('resultsLoading');

            },
            
            success: function(resultHtml) {
                
                // Show result
                $('#searchResults').html(resultHtml);

                // Bind result links
                bindResultsLinks();
                
            }
            
        });
        
    }
    
    /*
     * Setup delete confirmation
     */
    
    // Add click event handler
    $('.confirmDelete').click(function(e) {
        
        // Check title
        if ($(this).attr('title').length > 0) {
            
            // Get title
            var title = $(this).attr('title');
            
            // Lowercase first letter in title
            title = title.charAt(0).toLowerCase() + title.substr(1);
            
            // Set message
            var msg = 'Are you sure you want to ' + title + '?';
            
        } else {
            
            // Use default message
            var msg = 'Are you sure?';
            
        }
        
        // Confirm
        return confirm(msg);
        
    });
    
    /*
     * Setup expanding options textareas
     */
    
    // Turn of text wrapping and scrolling
    $('.expandingOptions').attr('wrap', 'off');
    $('.expandingOptions').css('overflow', 'hidden');
    
    // Check if body loaded
    $(window).load(function()
    {
        
        // Loop
        $('.expandingOptions').each(function() {

            // Adjust textarea height
            adjustOptionsHeight($(this).attr('id'));
            
        });
        
    });
    
    // Add onChange event handler
    $('.expandingOptions').keyup(function(e){
        
        // Adjust textarea height
        adjustOptionsHeight($(this).attr('id'));
        
    });
    
    // Adjust options textarea height
    function adjustOptionsHeight(textareaId)
    {
        
        // Prefix id
        textareaId = '#' + textareaId;
        
        // Get number of lines
        var numLines = $(textareaId).val().split("\n").length;
        
        // Get line height
        var lineHeight = $(textareaId).css('line-height').replace('px', '');
        
        // Update height
        $(textareaId).css('height', numLines * lineHeight);
        
    }
    
    /*
     * Setup tree lists
     */
    
    // Assign toggle action to toggle icons
    $('.toggleTreeList').click(function(e) {
        
        // Get element id
        var elementId = $(this).attr('id');
        
        // Get tree list id
        var treeListId = elementId.substring(18, elementId.length);
        
        // Toggle tree list
        toggleTreeList(treeListId);
        
    });
    
    // Toggle tree list function
    function toggleTreeList(parentId)
    {
        
        // Get list id
        var listId = 'treeListParentId' + parentId;
        
        // Check if list exists
        if ($('#' + listId).length) {
            
            // Get icon urls
            var plusIconUrl = iconsUrl + '/plus.gif';
            var minusIconUrl = iconsUrl + '/minus.gif';
            
            // Get icon id
            var iconId = 'treeListToggleIcon' + parentId;
            
            // Get cookie prefix
            var cPrefix = cookieKey + '[treeList][' + escape(parentId) + ']=';
            
            // Check if list visible
            if ($('#' + listId).css('display') == 'block') {
                
                // Hide list
                $('#' + listId).css('display', 'none');
                
                // Set icon to plus
                $('#' + iconId).attr('src', plusIconUrl);
                
                // Set cookie
                document.cookie = cPrefix + escape(0);
                
            } else {
                
                // Show list
                $('#' + listId).css('display', 'block');
                
                // Set icon to minus
                $('#' + iconId).attr('src', minusIconUrl);
                
                // Set cookie
                document.cookie = cPrefix + escape(1);
                
            }
        
        }
        
    }
    
    // Drop-down timeout timer id
    var dropdownTimeout = 0;
    
    /*
     * Show drop-down menu
     */
    function showDropDown()
    {
        
        // Check if timer running
        if (dropdownTimeout > 0) {
           
           // Clear timer
           clearTimeout(dropdownTimeout);
        
        }
        
        // Show drop-down menu
        document.getElementById('dropdown').style.display = 'block';
        
    }
    
    /*
     * Hide drop-down menu
     */
    function hideDropDown()
    {
        
        // Check if timer running
        if (dropdownTimeout > 0) {
           
           // Clear timer
           clearTimeout(dropdownTimeout);
        
        }
        
        // Show drop-down menu
        document.getElementById('dropdown').style.display = 'none';
        
    }
    
    /*
     * Start timer for hiding drop-down
     */
    function timeoutDropDown()
    {
        
        // Check if timer running
        if (dropdownTimeout > 0) {
           
           // Clear timer
           clearTimeout(dropdownTimeout);
        
        }
        
        // Start timer
        dropdownTimeout = setTimeout(hideDropDown, 400);
        
    }

});