var message;

var logEnabled = false;

// Variables where the results of AJAX calls are stored.
var submenuPublications;

var navTimer;

/**
 * Function for adding events to menu and submenu elements (using closures).
 * @param string id of menu element
 * @param string id submenu element
 */ 
function mouseFactory(menu, submenu)
{
    var e1 = document.getElementById(menu);
    var e2 = document.getElementById(submenu);
    
    if (e1)
    {
        e1.onmouseover = function() 
        {
            navTimer = setTimeout(function()
            {
                e2.style.display = 'block';
            }, 200);
        }
        
        e1.onmouseout = function() 
        {
            clearTimeout(navTimer);
            e2.style.display = 'none';
        }
        
        e2.onmouseover = function() 
        {
            e2.style.display = 'block';
        }
        
        e2.onmouseout = function() 
        {
            e2.style.display = 'none';
        }
    }
}

/**
 * Code executed when the whole document is loaded.
 */ 
$(document).ready(function()
{
    /**
     * Attaching the null console in case browser does not support one
     * so it won't throw errors while debugging.
     */
    if( !window.console ) 
    {
        window.console = 
        {
            error: function() {},
            group: function() {},
            groupEnd: function() {},
            info: function() {},
            log: function() {},
            warn: function() {}
        };
    }

    var firstSearch = true;
    
    // Remove text from search box when user clicks on it
    $("#homepage-keywords").click(function()
    {
        if (firstSearch == true)
        {
            this.value = '';
        }

        firstSearch = false;
    });

    $("#about #keywords").click(function()
    {
        if (firstSearch == true)
        {
            this.value = '';
        }

        firstSearch = false;
    });


    setOverlayDefaults();

    // Show/hide submenus.

    // About.
    mouseFactory('menu-about', 'submenu-about');
    
    // Services.
    mouseFactory('menu-services', 'submenu-services');
    
    // Publications.
    mouseFactory('menu-publications', 'submenu-publications');
    
    $("#menu-publications").mouseover(function()
    {
        if (typeof(submenuPublications) === 'undefined')
        {
            var result = ajaxCall({type: 'GET', url: '/ajax/publications'});
            
            if (result.success)
            {
                submenuPublications = result.data
                $("#submenu-publications").append(submenuPublications);
            }
        }
    });
    
    var firstSearch = true;
    
    // Remove text from search box when user clicks on it for the first time.
    $("#navbar-search").click(function()
    {
        if (firstSearch == true)
        {
            this.value = '';
        }
        
        firstSearch = false;
    });
    
    // Display page with information about what feed formats to choose in overlay.
    $("#help-formats").click(function()
    {
        showAjaxOverlayMessage('/ajax/formats', 780, 400, false);
        return false;
    });
    
    // Display page with information about NFM pro version.
    $(".help-pro").click(function()
    {
        showAjaxOverlayMessage('/ajax/pro', 780, 400, false);
        return false;
    });
    
    // Display search tips.
    $("#help").click(function()
    {
        showAjaxOverlayMessage('/ajax/search_tips', 780, 400, false);
        return false;
    });
    
    // Show get code dialog.
    $(".show-code").click(function()
    {
        var feedId = this.hash.slice(1);
    
        var result = ajaxCall({url: '/ajax/code', data: 'id=' + feedId});

        if (result.success)
        {
            message = '<div id="overlay">Copy this code to use it on Your site:<br />'
                    + '<div><textarea cols="50" rows="3">' + result.data + '</textarea></div></div>';
                    
            showOverlayMessage(message, 470, 140, true);
        }

        return false;
    });
    
    // Show rename feed dialog.
    $(".rename").click(function()
    {
        var name = $(this).attr('rel');
        var feedId = this.hash.slice(1);
        
        message = '<div id="overlay"><div>Rename feed<br /><strong>' + name + '</strong></div>'
                + '<form id="rename-feed" action="/feeds/rename/' + feedId +'" method="post">'
                + '<input type="text" size="40" id="name" name="name" value="' + htmlentities(name) + '" /><br /><br />'
                + '<input type="image" id="submit" src="/images/bt_save_changes.png" />'
                + '</form></div>';
        
        showOverlayMessage(message, 330, 190, true);
        
        // user confirms renaming of newsletter
        $("#rename-feed").submit(function()
        {
            // newsletter name is empty
            if ($("#name").val() == '')
            {
                $("#error").remove();
                $("#overlay").children(":first").before('<div id="error">No newsletter name given</div>');

                return false;
            }
        });
        
        return false;
    });
    
    // Show delete feed dialog.
    $(".delete").click(function()
    {
        var feedId = this.hash.slice(1);
    
        message = '<div id="overlay">Would you like to delete the feed?<br /><br />'
                + '<form id="delete-feed" action="/feeds/delete/' + feedId +'" method="post">'
                + '<input type="image" id="yes" src="/images/bt_confirm.png" />'
                + '</form></div>';

        showOverlayMessage(message, 300, 200, true);
        return false;
    });
    
    // Show message when free account user exceeded the limit of feeds and is trying to create a new one.
    $("#create-feed-forbidden").click(function()
    {
        message = '<div id="overlay" style="width: 300px;">Only Pro users can create more than 1 feed. <a href="/account/upgrade">Upgrade</a> your account to be able to create more feeds.</div>'

        showOverlayMessage(message, 300, 200, true);

        return false;
    });
});

/**
 * General AJAX routine.
 * @param JSON Object objParams AJAX parameters
 * @return JSON Object received data object
 */
function ajaxCall(objParams) 
{
    if (logEnabled)
    {
        console.group('ajaxCall(', objParams, ')');
    }

    var value;

    $.ajax(
    {
        async: false,
        cache: true,
        data: objParams.data || '',
        dataType: 'json',
        type: objParams.type || 'GET',
        url: objParams.url,
        success: function(response) 
        {
            value = response;
        
            if (logEnabled)
            {
                if (response.success) 
                {
                    console.info('AJAX response successfull');
                } 
                else 
                {
                    console.warn('AJAX response successfull, but server returned error');
                }
            }
        },
        error: function(xhr, errorMessage, thrownError) 
        {
            value = 
            {
                success: false,
                data: 
                {
                    errorCode: 0,
                    errorDescription: errorMessage
                }
            };
        
            if (logEnabled)
            {
                console.error('AJAX response error: ', errorMessage);
            }
        }
    });

    if (logEnabled)
    {
        console.info('ajaxCall successfull');
        console.groupEnd();
    }

    return value;
}

/**
 * Set default styling of the overlay layer
 */
function setOverlayDefaults()
{
    // set overlay defaults
  	$.blockUI.defaults.fadeIn = 0;
  	$.blockUI.defaults.fadeOut = 0;
  	$.blockUI.defaults.css['background-color'] = '#fff';
  	$.blockUI.defaults.css['padding'] = '20px';
  	$.blockUI.defaults.css['width'] = 'auto';
  	$.blockUI.defaults.css['height'] = 'auto';
  	$.blockUI.defaults.css['margin-left'] = '0';
  	$.blockUI.defaults.css['margin-top'] = '0';
  	$.blockUI.defaults.css['cursor'] = 'auto';
  	$.blockUI.defaults.css['text-align'] = 'center';
}

/**
 * Show message in overlay.
 * @param string message
 * @param int with
 * @param int height
 * @param bool forms should have different styles
 * @return false
 */
function showOverlayMessage(message, width, height, form)
{
    if (form)
    {
        $.blockUI.defaults.css['background-color'] = '#eee';
        $.blockUI.defaults.css['padding'] = '10px';
    }
    
    // Add close button
    message += '<input type="image" id="no" src="/images/bt_close.png" />';
    
    centerOverlay(width, height);

    // Block the application window.
    $.blockUI({ message: message });

    // The close button should react to escape key.
    addEscapeHandler();

    // User uses the close button.
    $("#no").click(function()
    {
        $.unblockUI();
        setOverlayDefaults();
    });
    
    return false;
}

/**
 * Show page loaded via AJAX in overlay.
 * @param string url - url of page that should be displayed
 * @param int width
 * @param int height
 * @param bool forms should have different styles
 * @return false
 */
function showAjaxOverlayMessage(url, width, height, form)
{
    var result = ajaxCall({url: url, data: ''});
    
    if (result.success)
    {
        showOverlayMessage(result.data, width, height, form);
    }

    return false;
}

/**
 * Center the overlay box
 * @param int width
 * @param int height
 */
function centerOverlay(width, height)
{
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();

    var top = windowHeight - (windowHeight / 2) - height / 2;
    var left = windowWidth - (windowWidth / 2) - width / 2;

    $.blockUI.defaults.css['top'] = top + 'px';
    $.blockUI.defaults.css['left'] = left + 'px';
}

/**
 * Set escape key to trigger cancel button event in dialogs
 * @return void
 */
function addEscapeHandler()
{
    // set the escape key to trigger cancel button event
    $("*").keypress(function(event)
    {
        // escape
        if (event.keyCode == 27)
        {
            $('#no').triggerHandler('click');
        }
    });
}

/**
 * Convert special characters in string to HTML entities
 * @param string str
 * @return string
 */
function htmlentities(str)
{
    var converted = $("<div/>").text(str).html();
    return converted.replace(/\"/g, "&quot;");
}

