/*=============================================================
Type:				Baringa Partners website - main javascript file
Build by:			VGroup
Document Author:	Mark Perkins
Author Email:		mark.perkins@vgroup.com
Copyright: 			(c) VGroup 2008	
---------------------------------------------------------------
Creation Date:		06-11-2008
============================================================ */

var unapartners = function()
{
	
	var editing;
	
	var currentPage;
	
	var colourSchemeArray = [ "one", "two", "three", "four", "one", "two", "three", "four", "three", "four", "one", "two", "three", "four", "one", "two", "one", "two", "three", "four", "one", "two", "three", "four" ];
	
	var peopleColourSchemeArray = [ "one", "two", "three", "four", "one", "two", "three", "four", "one", "two", "three", "four", "one", "two", "three", "four", "one", "two", "three", "four", "one", "two", "three", "four" ];
	
	// colour the sub nav blocks according to schemes
	var colourBlocks = function()
	{
		var colourBlocks = $("#block_nav li");
		if ( colourBlocks.size() )
		{
			colourBlocks.each(function(i){
				$(this).addClass( "scheme_"+colourSchemeArray[i] );
			});
		}
		
		var peopleBlocks = $(".person");
		if ( peopleBlocks.size() )
		{
			peopleBlocks.each(function(i){
				$(this).addClass( "scheme_"+peopleColourSchemeArray[i] );
			});
		}
	};
	
	var setUpPeopleLoader = function()
	{
		$(".person:not(.current)").expire("click");
		$(".person.current").expire("click");
		
		$(".person:not(.current)").livequery("click", function(){

			var person = $(this);

			var img = $(this).find("img");
			var imgsrc = img.attr("src");
			img.hide();
			var loader = $('<img class="loader" src="/cssimages/ajax-loader.gif" style="height:32px; width: 32px; opacity: 1; margin-top: 25px; margin-left: 36px" />');
			img.parent().append( loader );
			
			var hiddenTransitionPanel = $("<div></div>").hide();
			
			$("#column1").height($("#column1").height());
			
			$("#column1 > *").fadeOut();
			
			hiddenTransitionPanel.load( $(this).find("a").attr("href") + " #column1 > *", function(){
		
				$("#column1").html( hiddenTransitionPanel.html() );
				
				$("#column1 > *").hide();

				$("#column1 > *").fadeIn();
				
				$("#column1").height("auto");
				
				$(".person.current").removeClass( "current" );
				person.addClass("current");
				
				loader.remove();
				img.show();
				
				return false;
			});
			
			return false;
			
		});
		
		$(".person.current").livequery("click",function(){ return false; });
	}
	
	var pages_array = [];
	var currentIndex = null;
	
	var setUpPager = function()
	{
		var pageslist_items = $("#main_nav li a");
		
		var this_page_parts = location.href.split("#");
		var url = this_page_parts[0];
		
		pageslist_items.each(function( i, val ) {
			
			pages_array.push($(val).attr("href"));
			if ( val == url ) currentIndex = i;		
		});
			
		var pager = $('<div id="pager"><a href="#" class="prev">prev</a><a href="#" class="next">next</a></div>');
		$("#header").append(pager);
		
		var next = pager.find( ".next" );
		var prev = pager.find( ".prev" );
		
		setPagerLinks();

		// checkNav( oldIndex, currentIndex );
		next.click(function(e){
			$("#content > *").fadeOut();
			$("#content").height($("#content").height());
	
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');

			$.historyLoad(hash, "next");
			return false;
		});
		
		prev.click(function(){
			$("#content > *").fadeOut();
			$("#content").height($("#content").height());

			var hash = this.href;
			hash = hash.replace(/^.*#/, '');

			$.historyLoad(hash, "prev");
			return false;
		});
		
		var thisLi = $("#main_nav li a[href="+pages_array[currentIndex]+"]").parent("li");
		
		if (  ! thisLi.next("li").size() && ! thisLi.find("ul").size()  )
		{
			$("#pager .next").css("visibility","hidden");
		}
		
		setPagerVisibility( thisLi );
		
	};

	
	var checkNav = function( oldIndex, currentIndex )
	{
		var currentLi = $("#main_nav li a[href="+pages_array[currentIndex]+"]").parent("li");
		var prevLi = $("#main_nav li a[href="+pages_array[oldIndex]+"]").parent("li");

		if ( prevLi.parent("ul").parent("li").size() )
		{
			prevLi.removeClass("current");
		}
		
		currentLi.addClass("current");

		setPagerVisibility( currentLi );
		
	};
	
	var setPagerVisibility = function( currentLi )
	{
		if ( currentLi.size() )
		{
			var level = getLevel( currentLi );
		
			if ( level == 1 || ( level == 2 && hasChildLi( currentLi ) && ! isFirstChild( currentLi ) ) ) 
			{
				$("#pager .prev").css("visibility","hidden");
			}
			else
			{
				$("#pager .prev").css("visibility","visible");
			}
				
			if ( (isLastChild( currentLi ) && !hasChildLi( currentLi ) ) || isFirstChild( currentLi ) && getLevel( currentLi ) == 1 )
			{
				$("#pager .next").css("visibility","hidden");
			}
			else
			{
				$("#pager .next").css("visibility","visible");
			}
		}
		else
		{
			$("#pager .next").css("visibility","hidden");
			$("#pager .prev").css("visibility","hidden");
		}
		

	
	}
	
	var getLevel = function( currentLi )
	{
		if ( currentLi.parent("ul").parents("ul").parents("ul").size() ) return 3;
		else if ( currentLi.parent("ul").parents("ul").size() ) return 2;
		else if ( currentLi.parent("ul").size() ) return 1;
	};
	
	var hasNextLi = function( currentLi )
	{
		return currentLi.next("li").size();
	};
	
	var hasPrevLi = function( currentLi )
	{
		return currentLi.prev("li").size();
	};
	
	var hasParentLi = function( currentLi )
	{
		return currentLi.parent("ul").parent("li").size();
	};
	
	var hasChildLi = function( currentLi )
	{
		return currentLi.children("ul").children("li").size();
	};	
	
	var isFirstChild = function( currentLi )
	{
		return currentLi.is(":first-child");
	};
	
	var isLastChild = function( currentLi )
	{
		return currentLi.is(":last-child");
	};
	
	var setPagerLinks = function()
	{
		var index = currentIndex;
		var prev = ( pages_array[index-1] !== undefined ) ? pages_array[index-1] : "#";
		var next = ( pages_array[index+1] !== undefined ) ? pages_array[index+1] : "#";
		$("#pager .prev").attr( "href", prev );
		$("#pager .next").attr( "href", next );
	}

	var initBlockLinks = function()
	{
		var lastcolour = null;

		var colourblock = $(".colourblock");

		colourblock.css("cursor","pointer");

		colourblock.click(function(){
			window.location.href = $(this).find("p.more a").eq(0).attr("href");
		});

		colourblock.mouseover(function(){
			lastcolour = $(this).css("background-color");
			$(this).css("background-color", $(this).find('p.more').css("background-color"));
		}).mouseout(function(){
			$(this).css("background-color", lastcolour);
		});
	};

	var initPrintLinks = function()
	{
		$(".printlink").click(function(){
			window.print();
			return false;
		}).show();
	};

	var initMiscFixes = function()
	{
		if ( ! editing ) $("img[src=]").remove();
		
		var date = new Date();
		$(".year").text( date.getFullYear() );
	};
	
	var setUpNews = function()
	{
		// set up the filters 
		var filter = $("#filter").show();
		
		filterList( filter );
		
		filter.find("input[type=checkbox]").click(function(){
			filterList( filter );
			pageify( "div.vis", "#article_pager", currentPage, 10 );
		});
		
		// set up the pagination
		pageify( "div.vis", "#article_pager", 1, 10 );
	};
	
	var filterList = function( filter )
	{
		$("div.article_item").removeClass("vis").hide();
		var checked = "";
		filter.find("input[type=checkbox]:checked").each(function(){
			$("div."+$(this).attr("name")).addClass("vis").show();
		});
		
		if ( ! $("div.vis").size() )
		{
			if ( ! $("p.no_items").size() ) $("#filter").after('<p class="no_items">There are no matching articles</p>');
			$("#article_pager").hide();
		}
		else
		{
			$("p.no_items").remove();
			$("#article_pager").show();
		}
	};
	
	var pageify = function( elements, controls, startpage, startPP )
	{	
		var controls = $(controls);
	
		var perpage;
	
		var numrows;
	
		var numpages;
	
		var rows;
	
		rowGroups = new Array();
	
		var appendControls = function()
		{
			var pager = '<a class="prev" href="#">prev</a><span class="counter">page <span class="pagenum"></span> of <span class="pagetotal"></span></span><a class="next" href="#">next</a>';

			controls.each(function(){
				$(this).html( pager );
				$(this).find(".pagenum").text(currentPage);
				$(this).find(".pagetotal").text(numpages);
				controls.show();
			});
			
			$(".prev").click(function(){
				currentPage = currentPage - 1;
				showPage( currentPage );
				$(".pagenum").text(currentPage);
				checkControlLinks();
				return false;
			});
			
			$(".next").click(function(){
				currentPage = currentPage + 1
				showPage( currentPage );
				$(".pagenum").text(currentPage);
				checkControlLinks();
				return false;
			});
			
			checkControlLinks();
		};
		
		var checkControlLinks = function()
		{
			if ( currentPage == 1 ) $(".prev").hide();
			else $(".prev").show();
			
			if ( currentPage == numpages ) $(".next").hide();
			else $(".next").show();
		};
	
		var rowchange = function(){
			// a row has been added or removed, reset the paging
			
		};
	
		var categoriseRows = function()
		{
			// split rows up
			var lowerbound = 0;
			var upperbound = perpage -1;
		
			for ( var i = 0; i <  numpages; i++ )
			{
				rowGroups[i] = rows.slice( lowerbound, upperbound + 1 );
				lowerbound = upperbound + 1;
				upperbound = upperbound + perpage;
			}
		};
	
		var showPage = function( page )
		{
			page = page - 1; // array starts at 0, page numbers start at 1
			if ( rowGroups[page] !== undefined && rowGroups[page] !== null )
			{
				rows.hide();
				rowGroups[page].show();
			}
		};
	
		var init = function()
		{	
			rows = $(elements);
			
			if ( rows.size() )
			{
				numrows = rows.size();

				perpage = ( startPP !== undefined && startPP !== null ) ? startPP : 10;
		
				currentPage = ( startpage !== undefined && startpage !== null ) ? startpage : 1;

				numpages = Math.ceil( numrows / perpage );

				if (currentPage > numpages ) currentPage = numpages;

				categoriseRows();
		
				showPage( currentPage );
		
				rows.bind("tablepageify.rowchange", rowchange );
			
				appendControls();
			}

		}();

	};
	
	 function pageload(hash, dir) {
		// hash doesn't contain the first # character.
		if(hash) {
			if ( dir )
			{
				$("p#overview").fadeOut();
				// restore ajax loaded state
				$("#content").load( hash+" #content > *", function(){
					$("#content > *").hide();

					oldIndex = currentIndex;

					if ( dir == "next") currentIndex = currentIndex+1;
					else  currentIndex = currentIndex-1;
					setPagerLinks();
					$("#content > *").fadeIn();
					$("#content").height("auto");
					
				
					$("p#overview").load( hash+" p#overview span", function(){
						$("p#overview").fadeIn();
					});
					
					checkNav( oldIndex, currentIndex );
					
					unapartners.init( true );
				});
			}
			else
			{

				// first visit to the page, not paging thru
				$("p#overview").hide();
				$("#content").load( hash+" #content > *", function(){
					
					// $("p#overview").fadeOut();
					$("p#overview").load( hash+" p#overview span", function(){
						$("p#overview").fadeIn();
					});
					
					var hashparts = location.href.split("#");
					
					var thisLi = $("#main_nav li a[href="+hashparts[1]+"]").parent("li");
					
					if ( thisLi.parent("ul").parent("li").size() )
					{
						thisLi.siblings().removeClass("current");	
					}
					else
					{
						thisLi.find("ul li").removeClass("current");
					}

					thisLi.addClass("current");
					
					if ( ! thisLi.parent("ul").parent("li").size() )
					{
						// doesnt have a parent, so is a top level page
						$("#pager .prev").css("visibility","hidden");
						
						if ( ! thisLi.find("li").size() )
						{
							$("#pager .next").css("visibility","hidden");
						}
						else
						{
							$("#pager .next").css("visibility","visible");
						}
					}
					else
					{
						$("#pager .prev").css("visibility","visible");
					}
					
				});
			}
		}
	}
	
	var initMainMenu = function() {
		
	  $('#main_nav').hoverAccordion({keepheight:false});
	
		// $("#main_nav > li").hover(function(){
		// 
		// 	$(this).addClass("open");
		// 	$(this).children("ul").slideDown("slow");
		// 	
		// }, function(){
		// 	$(this).removeCLass("open");
		// });
		// 
		// $("#main_nav > li ul").hover(function(){ 
		// 
		// 	if ( ! $(this).parent("li").hasClass("open") )
		// 	{
		// 		$(this).slideUp();
		// 	}
		// 	
		// 	// $("#main_nav > li ul").slideUp("slow", function(){
		// 	// 	
		// 	// 	// $(this).removeCLass("open");
		// 	// 	
		// 	// });
		// 	
		// },function(){});
		
	};
	
	return {
	
		init : function( refresh )
		{
			if ( refresh === undefined ) refresh = false;
			
			editing = $(".editing").size(); // whether we are in edit mode or not
			
			colourBlocks();
			initPrintLinks();
			initMiscFixes();
			setUpNews();
			
			if ( ! editing ) initBlockLinks();
			
			if ( ! editing && $(".people_section").size() ) setUpPeopleLoader();


			if ( ! refresh && ! editing )
			{
				if ( ! ( $.browser.msie && $.browser.version == 6 ) )
				{
					setUpPager();
					
					$.historyInit(pageload);
					var hashparts = location.href.split("#");
			
					if ( hashparts[1] !== undefined ) $("#content").empty();			
				}
				
				// initMainMenu();
				
				$("a[href=]").css("background","none");
				$("a[href=]").parent("li").parent("ul").css("margin-left", "0").find("li ul").css("padding-left","10px");
				
				var firstp = $("#column2 p:first-child");
				if ( firstp.find("img").size() ) firstp.css( "margin-top", "0" );
			
			}
		}
		
	};
	
}();

$(function(){ unapartners.init(); });

(function($){
    $.fn.hoverAccordion = function(options){

        options = jQuery.extend({
            speed: 'fast', 
            activateitem: 'true', 
            active: 'active', 
            header: 'header', 
            hover: 'hover', 
            opened: 'opened', 
            closed: 'closed', 
            keepheight: 'true' 
        }, options);
        
        // Current hover status
        var thislist = this;
        
        // Current URL
        var thisurl = window.location.href;
        
        // Interval for detecting intended element activation
        var i = 0;
        
        // Change display status of subitems when hovering
        function doHover(obj){
            if ($(obj).html() == undefined) 
                obj = this;
            
            // Change only one display status at a time
            if (!thislist.is(':animated')) {
                var newelem = $(obj).parent().children('ul');
                var oldelem = $(obj).parent().parent().children('li').children('ul:visible');
                if (options.keepheight == 'true') {
                    thisheight = maxheight;
                }
                else {
                    thisheight = newelem.height();
                }
                
                // Change display status if not already open
                if (!newelem.is(':visible')) {
                    newelem.children().hide();
                    newelem.animate({
                        height: thisheight
                    }, {
                        step: function(n, fx){
                            newelem.height(thisheight - n);
                        },
                        duration: options.speed
                    }).children().show();
                    
                    oldelem.animate({
                        height: 'hide'
                    }, {
                        step: function(n, fx){
                            newelem.height(thisheight - n);
                        },
                        duration: options.speed
                    }).children().hide();
                    
                    // Switch classes for headers
                    oldelem.parent().children('a').addClass(options.closed).removeClass(options.opened);
                    newelem.parent().children('a').addClass(options.opened).removeClass(options.closed);
                }
            }
        };
        
        var itemNo = 0;
        var maxheight = 0;
        
        // Setup initial state and hover events
        $(this).children('li').each(function(){
            var thisitem = $(this);
            
            itemNo++;
            
            // Set current link to current URL to 'active' and disable anchor links
            var thislink = thisitem.children('a');
            
            if (thislink.length > 0) {
                // Hover effect for all links
                thislink.hover(function(){
                    $(this).addClass(options.hover);
                }, function(){
                    $(this).removeClass(options.hover);
                });
                
                var thishref = thislink.attr('href');
                
                if (thishref == '#') {
                    // Add a click event if the header does not contain a link
                    thislink.click(function(){
                        doHover(this);
                        this.blur();
                        return false;
                    });
                }
                else 
                    if (options.activateitem == 'true' && thisurl.indexOf(thishref) > 0 && thisurl.length - thisurl.lastIndexOf(thishref) == thishref.length) {
                        thislink.parent().addClass(options.active);
                    }
            }
            
            var thischild = thisitem.children('ul');
            
            // Initialize subitems
            if (thischild.length > 0) {
                if (maxheight < thischild.height()) 
                    maxheight = thischild.height();
                
                // Change appearance of the header element of the active item
                thischild.children('li.' + options.active).parent().parent().children('a').addClass(options.header);
                
                // Bind hover events to all subitems
                thislink.hover(function(){
                    var t = this;
                    i = setInterval(function(){
                        doHover(t);
                        clearInterval(i);
                    }, 400);
                }, function(){
                    clearInterval(i);
                });
                
                
                // Set current link to current URL to 'active'
                if (options.activateitem == 'true') {
                    thischild.children('li').each(function(){
                        var m = $(this).children('a').attr('href');
                        if (m) {
                            if (thisurl.indexOf(m) > 0 && thisurl.length - thisurl.lastIndexOf(m) == m.length) {
                                $(this).addClass(options.active).parent().parent().children('a').addClass(options.opened);
                            }
                        }
                    });
                }
                else 
                    if (parseInt(options.activateitem) == itemNo) {
                        thisitem.addClass(options.active).children('a').addClass(options.opened);
                    }
            }
            
            // Close all subitems except for those with active items
            thischild.not($(this).parent().children('li.' + options.active).children('ul')).not(thischild.children('li.' + options.active).parent()).hide().parent().children('a').addClass(options.closed);
        });
        
        return this;
    };
    
})(jQuery);

$(function(){
    $('body').addClass('hasJS');
    
    $('.newsticker_wrapper').hide().slideDown(function(){
        $('.newsticker').fadeIn();
        $('.newsticker').newsticker({wait  : 3000});        
    });

});

swfobject.registerObject("baringaflash", "9.0.0", "/swf/expressInstall.swf");