var message;

var logEnabled = true;

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

/**
 * Add events to menu and submenu elements when page loads
 */ 
window.onload = function() 
{     
    // show/hide submenus

    // about
    mouseFactory('menu-about', 'submenu-about');
    
    // services
    mouseFactory('menu-services', 'submenu-services');
    
    // publications
    mouseFactory('menu-publications', 'submenu-publications');
    
    // advertise
    mouseFactory('menu-advertise', 'submenu-advertise');
};

// new window function

$(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() {}
        };
    }

    setOverlayDefaults();

    // show card security code page in overlay
    $("#card-security").click(function()
    {
        var result = ajaxCall({url: '/ajax/csc', data: ''});
        
        if (result.success)
        {   
            centerOverlay(820, 440);
         
            result.data += '<input type="image" id="no" src="/images/button_close.png" />';
            
            $.blockUI({ message: result.data });
            
            addEscapeHandler();
            
            // user cancels the dialog
            $("#no").click(function() 
            { 
                $.unblockUI();
                setOverlayDefaults();
            });
        }
        
        return false;
    });
    
    // show user agreement page in overlay
    $("#user-agreement").click(function()
    {
        var result = ajaxCall({url: '/ajax/user-agreement', data: ''});
    
        if (result.success)
        {            
            centerOverlay(740, 440);
            
            result.data += '<input type="image" id="no" src="/images/button_close.png" />';
            
            $.blockUI({ message: result.data });
            
            addEscapeHandler();
            
            // user cancels the dialog
            $("#no").click(function() 
            { 
                $.unblockUI();
                setOverlayDefaults();
            });
        }
        
        return false;
    });
  
    // show list of EIN news publications in overlay
    $(".publications").click(function()
    {
        var result = ajaxCall({url: '/ajax/publications', data: ''});
        
        if (result.success)
        {            
            centerOverlay(740, 440);
            
            result.data += '<input type="image" id="no" src="/images/button_close.png" />';
            
            $.blockUI({ message: result.data });
            
            addEscapeHandler();
            
            // open links with rel="external" attribute in new window
          	$("a[rel=external]").click(function(){
            		window.open(this.href);
            		return false;
          	});
            
            // user cancels the dialog
            $("#no").click(function() 
            { 
                $.unblockUI();
                setOverlayDefaults();
            });
        }
        
        return false;
    });
  
  
    // open links with rel="external" attribute in new window
  	$("a[rel=external]").click(function(){
    		window.open(this.href);
    		return false;
  	});
    
    // show warning message that use is going to lose the rest of his credits
  	$("#renew #submit").click(function()
  	{  	
        var remaining = $("#pr-count").text();
        
        // user has remaining press releases
        if (remaining > 0)
        {
            // show warning
            centerOverlay(330, 140);
              
            var data;
            data  = '<div id="overlay">You still have <strong>' + remaining  + '</strong> credit(s) remaining in your account.<br /> If you renew/upgrade now, those credits will be lost.<br /><br />Renew/Upgrade now?<br /><br />'
                  + '<input type="image" id="yes" src="/graphics/common/button_confirm_big.png" />'
                  + '<input type="image" id="no" src="/images/button_close.png" /></div>';
            
            // block the application window
            $.blockUI({ message: data });
            
            addEscapeHandler();
            
            // user cancels the dialog
            $("#no").click(function() 
            { 
                $.unblockUI();
                setOverlayDefaults();
            });
            
            // user confirms the renewal
            $("#yes").click(function() 
            {
                $.unblockUI();
                setOverlayDefaults();
                $("#renew").submit();
                return true;
            });
            
            return false;
        }
        else
        {
            return true;
        }
    });
});
	
/**
 * 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: false,
    		data: objParams.data || '',
    		dataType: 'json',
    		type: objParams.type || 'POST',
    		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';
}

/**
 * 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');
        }
    });
}