$(document).ready(function() {

    function megaHoverOver(){
        $(this).find(".sub").stop().fadeTo('fast', 1).show();
        $(this).addClass('hover');
       
        //Calculate width of all ul's
        (function($) {
            jQuery.fn.calcSubWidth = function() {
                rowWidth = 0;
                //Calculate row
                $(this).find("ul").each(function() {               
                    rowWidth += $(this).width();
                });
            };
        })(jQuery);
   
        if ( $(this).find(".row").length > 0 ) { //If row exists...
            var biggestRow = 0;
            //Calculate each row
            $(this).find(".row").each(function() {                       
                $(this).calcSubWidth();
                //Find biggest row
                if(rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });
            //Set width
            $(this).find(".sub").css({'width' :biggestRow});
            $(this).find(".row:last").css({'margin':'0'});
       
        } else { //If row does not exist...
       
            $(this).calcSubWidth();
            //Set Width
            $(this).find(".sub").css({'width' : rowWidth});
       
        }
    }

    function megaHoverOut(){
      $(this).removeClass('hover');
      $(this).find(".sub").stop().fadeTo('fast', 0, function() {
          $(this).hide();
      });
    }


    var config = {
         sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
         interval: 0, // number = milliseconds for onMouseOver polling interval    
         over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
         timeout: 0, // number = milliseconds delay before onMouseOut    
         out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
    };



    $("ul#horizontal-nav li .sub").css({'opacity':'0'});
    $("ul#horizontal-nav li").hoverIntent(config);


        $("#horizontal-nav .homeLevel0").mouseenter(function() {
                   $(this).expose({color:"#000000",zIndex: 5, loadSpeed: 0, closeSpeed: 0, opacity: .6});
        });
        $("#horizontal-nav .homeLevel0").mouseleave(function(){
            $.mask.close();
        });

		
		$('a:contains("Diplomats@work")').each( function() {
            $(this).attr('href', '#').click( function(){
				window.open( '/diplomats-at-work/index?op=switchOffAdmin', "daw", "height=600, width=800, location=no, " );
		    });
		});
		
		if ($('.pagination')) { setupPagination() }


              
/*

                $('#feedbackBox').each( function() {
                        var left = ($(window).width()/2) - ($(this).width()/2);
                        $(this).css('left',left);
                         var t = setTimeout ( createFeedbackBox, 2000);
                });

                function createFeedbackBox () {
                        $('#feedbackBox').each ( function () {
			$(this).slideDown('slow').delay(6000).slideUp('slow');
                        });
		}
*/

});




var navHandler = function(){
	var level1;
	var level2;
	var level3;
	var link1;
		
	var init = function(obj,open){
		level1 = obj.children('li').addClass('level1');	//All li children of the slidenav
		level2 = level1.children('ul').addClass('ul-level2');	//All of the ul children of the level1 elements
		level3 = level2.find('ul').addClass('ul-level3');	//All of the ul children of the level2 elements
		link1 = level1.children('a').addClass('link1');	//All of the main links (learn, work, play)

		
		navHandler.unattach( link1 );	//Despite the counterintuitive name, attaches the initial mouseover events to the top level links
		
		link1.each( function(){
			if( !$(this).is(':contains("'+ open +'")')  )
				$(this).parent().css( 'width' , link1.outerWidth() );
			else {
				$(this).parent().find('.ul-level2').fadeIn('fast');
				$(this).addClass('on');
			}
		});

		level2.each( function(){
			$(this).css({
				'left' : link1.outerWidth() + 10 + 'px',
				'top' : '10px'
			});
			level2.find('li').each( function(){
				$(this).mouseover( function(){
					level2.find('ul').hide();
					//$(this).columns();
					$(this).find('ul').show();
				});
				
				//$(this).columns();	
			});
		});
		
		$(".ul-level3").each(function(){
                    if ($(this).parent().hasClass("current") || $(this).find("li").hasClass("current")){
                        $(this).css("display", "block");
					}

        });
	}
	var attach = function(obj){
		navHandler.unattach(obj);
	}
	var unattach = function(obj){
		obj.each(function(){
			$(this).mouseover( function(){
				if( $(this).hasClass('on') ) return false;
				obj.unbind();
				level1.animate({ 'width' : $(this).outerWidth() },'medium');
				link1.removeClass('on');
				$(this).addClass('on');
				$(this).parent().animate({ 'width' : '498px' }, 'medium', function(){ navHandler.attach(obj) });		
				$('.ul-level2, .ul-level3').css('display' , 'none');
				$(this).parent().find('.ul-level2').show();
                $(".ul-level3").each(function(){
                    if ($(this).parent().hasClass("current") || $(this).find("li").hasClass("current")){
                        $(this).css("display", "block");
					}

                });
			});	
		});
	}	
	
	return {
		init : function(obj,open){ init(obj,open) },
		attach : function(obj){ attach(obj) },
		unattach : function(obj){ unattach(obj) }
	}
}();


$.fn.columns = function() {
	var parentUl = $(this).find('ul');
	var tmp = $('<ul />');
	var h = 0;
	
	parentUl.show();	//A trick to force the ul into the dom as to measure the height of its children
	
	while( parentUl.outerHeight() > $('#slideNav').innerHeight() )
		parentUl.find('li:last').appendTo( tmp );

	tmp.find('li').each( function(index) {
		$(this).appendTo( parentUl ).css({
			'position' : 'absolute',
			'left' : '140px',
			'top' : h
		});
		h = $(this).outerHeight() + h;
	});			
	
	if( parentUl.find('a').hasClass('sub-on') )
		parentUl.show();
	else
		parentUl.hide();	//And then this conveniently hides it again
}






/*	ACCORDION SCRIPT
-------------------------------------------------------------------------------------------------------------------------*/
$( function(){
	$('.accordion').initAccordion();
});

$.fn.initAccordion = function(){

function setHeight(which) {
    var div = $(which);
    div.css({height: div.height()});
}

	//$(this).find('.scroll:first').show();
	//$(this).find('.header span:first').text('-');

	$(this).find('.header .expand').click( function(){
		if( $(this).is(':contains("+")') ){
                        setHeight($(this).parents('.box').find('.scroll'));
			$(this).parents('.box').find('.scroll').slideDown('fast');
			$(this).text('-');
		}
		else{
			$(this).parents('.box').find('.scroll').slideUp('fast');
			$(this).text('+');
		}
	}).hover( 
		function(){ $(this).addClass('on') },
		function(){ $(this).removeClass('on') }
	);
};


/* FORUMS PAGINATION SCRIPT
--------------------------------------------------------------------------------------------------------------------------*/
function setupPagination () {
	var numPaginationItems = $('.pagination ul li a.pa').size();

	var currentNum = parseInt($('.pagination li.active a.pa').html());
	var prevNum = currentNum - 1;
	var nextNum = currentNum + 1;

	if (prevNum > 0)
		$('#previous a').attr('href', '?pn=' + prevNum);

	if (nextNum <= numPaginationItems)
		$('#next a').attr('href', '?pn=' + nextNum);
}


