/* Plugin to use labels associated with form inputs as the default value
*/
(function($) { 
 	$.fn.extend({ 
		labeliseForm: function() { 
			return this.each(function() {
				obj = $(this);
				var tag = this.tagName.toLowerCase();
				if(tag == 'form')
					return $("label",this).labeliseForm();

				var label = obj.text();
				var input_id = obj.attr("for");

                if ( input_id == "" )
                    return;

				input = $("#"+input_id);

                // Make sure we don't hide checkbox labels
				if ( input.attr( 'type' ) == 'checkbox' )
				    return;
				
				input.attr('value', label).focus(function(){
					if ( $(this).attr('value') == label )
					{
						$(this).attr('value', '');
						$(this).addClass( 'searchBoxHighlighted' );
						$(this).removeClass( 'searchBoxLabel' );
					}
						
				}).blur(function(){
					if ( $(this).attr('value') == '' )
					{
						$(this).attr('value', label);
						$(this).addClass( 'searchBoxLabel' );
						$(this).removeClass( 'searchBoxHighlighted' );						
					}
				});
                $(this).hide();
			});
		}
	}); 
})(jQuery); 

// Allow items to be fully expanded for certain subtrees automatically
function expandAllChildren( selector ) {
    $("#leftNav " + selector + " ul.tertiary").show();
    $("#leftNav " + selector + " .expandable").removeClass('expandable').addClass('collapsable').children().removeClass('expandable-hitarea').addClass('collapsable-hitarea');
}


function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.attr( {
        style: "min-height: " + tallest + "px; height:auto !important; height:" + tallest + "px"
    });
    // group.height(tallest);
}

jQuery(document).ready(function(){
	/* Navigation */

    $( 'ul#leftNavFirstLevel li ul.leftNavSecondLevel').each( function() {
        var id = "#" + $(this).parent().attr( 'id' );
        $( id + " div a" ).before( '<span class="ctrl">+</span>' );
    });

    /* Hide and change text for any boxes that should be collapsed by default */
    $('ul#leftNavFirstLevel li.selected1 div span.ctrl').text('-');
    
    $("#leftNav ul ul").hide();
    $("#leftNav li.selected1 ul").show();

	
	$("#leftNav > ul > li > div > .ctrl").click(function(){
			var containerId = $(this).parent().parent()[0].id;
			if ( containerId != 'investor-home-nav' )
			{
				if ( $(this).text() == '-' )
				{
				    $("#leftNav ul.leftNavSecondLevel").slideUp("fast");
				    $(this).text( '+' );
				}
				else
				{
				    var cf_state = $( "#leftNav" ).find( ".ctrl" );
				    cf_state.text( '+' );			    
				    $("#leftNav ul.leftNavSecondLevel").slideUp("fast");
				    //$( "#ticker" ).slideUp("fast");

				    $(this).text( '-' );
				    $(this).parent().next().slideDown("fast");
				}
				
		        	$( "#leftNav li.selected2 ul.tertiary" ).show();
				/*
				if( containerId == 'primary-nav-2' ) {
    					expandAllChildren( 'li#primary-nav-2' );
				}
                */
			}
			return true;
	});
	
	$("#leftNav ul ul").treeview({
		collapsed: true,
		animated: 'fast'
	});
	
	var lastIteminPrimaryNavDropdown = $( "#primary-nav-1 .leftNavSecondLevel li.lastExpandable:last" );
	lastIteminPrimaryNavDropdown.removeClass( 'lastExpandable' );
		
    //Expand the nodes that should be expanded by default
    $("#leftNav li.defaultunfolded.expandable").removeClass('expandable').addClass('collapsable').children().removeClass('expandable-hitarea').addClass('collapsable-hitarea').show();

	/* TODO This is a bit rough and needs to be optimised */
    $("#leftNav li.selected2").removeClass('expandable').addClass('collapsable').children().removeClass('expandable-hitarea').addClass('collapsable-hitarea').show();
    
    var lastSelected = $( "#leftNav li.selected2" );
    if ( lastSelected.hasClass( 'lastExpandable' ) )
    {
        lastSelected.removeClass( 'lastExpandable' );
        lastSelected.addClass( 'lastCollapsable' );
        lastSelected.children().removeClass( 'lastExpandable-hitarea' );
        lastSelected.children().removeClass( 'lastCollapsable-hitarea' );
        lastSelected.children().show();
    }
    
	/* Homepage banner click */
	var featureWelcome = $(".feature-welcome");
	if( typeof( featureWelcome ) == "object" ) {
		featureWelcome.click(function(){
			document.location.href = $('#hpFeature1 a').attr( 'href' );	
		});
	}	

    //expandAllChildren( 'li#primary-nav-2.selected1' );

    /* Add opener & closers */
    $('div.minifeature h1').before('<span class="ctrl">-</span>');
    
    /* Hide and change text for any boxes that should be collapsed by default */
    $('#minifeatures .collapsed .ctrl').text('+');
    $('#minifeatures .collapsed .mf_inner').hide();

	$('#minifeatures .heading').click(function(){
		var heading = $(this);
		var cf = heading.parent();
		var cf_state = cf.find(".ctrl");
        // var of = heading.parent().parent().children().not( cf );
        // var of_state = of.find(".ctrl");
        // var clicked_closed = false;

		if (cf.length == 1 ) {
			if ( cf_state.text() == '-' )
			{
				cf.find(".mf_inner").slideUp("fast");
				cf_state.text('+');
                // clicked_closed = true;
			}
			else
			{
				cf.find(".mf_inner").slideDown("fast");
				cf_state.text('-');
			}
		}
        
        // if (of.length == 1 ) {
        //  if ( of_state.text() == '-' && !clicked_closed )
        //  {
        //      of.find(".mf_inner").slideUp("slow");
        //      of_state.text('+');
        //  }
        //  else
        //  {
        //      of.find(".mf_inner").slideDown("slow");
        //      of_state.text('-');
        //  }
        // }
		return false;
	}).css('cursor', 'pointer');
    
    $( ".mf_inner .more-details" ).click( function() {
        var parent = $(this).parent();
        var box = $(this).next().next();
        if ( box.is(":visible") )
        {
            $(this).next().next().slideUp( 'fast' );
            $(this).find( "a" ).text( 'More +' );
        }
        else
        {
            parent.removeAttr( 'height' );
            parent.removeAttr( 'style' );
            $(this).next().next().slideDown( 'fast' );
            $(this).find( "a" ).text( '-' );
        }

        return false;
    })   
    
    /* Add odd even classes to alternating table rows */
    $("table.zebra tr:odd").addClass("odd");
    $("table.zebra tr:even").addClass("even");

        $( "#search-form select" ).change(function() {
            var destinationUrl = $("option:selected", this).val();

            if( destinationUrl != '0' ) {
                window.location = destinationUrl;
            }
        }
    );

    /* Detect screen size to avoid fixed position is screen is too small */
    if ($(document).height()>=460 && jQuery.inArray( currentNode, longpages) != -1 ) {
        if (matrixIsHome) {
            $("div#leftPanel").addClass("fixhome");
            $("div#header").addClass("fixsplashhome");
            $("div#inner").addClass("fixcontenthhome");
        } else {
            $("div#leftPanel").addClass("fixcontent");
            $("div#header").addClass("fixsplashcontent");
            $("div#inner").addClass("fixcontenthcontent");
        }
    }
    
});



/*
 * Safari doesn't seem to like that we mess around with heights in 
 * jQuery(document).ready(function() so we're using this method instead.
 * adjustHeights() will be loaded after all images, etc have their proper
 * heights calculated.
*/
function adjustHeights(){
    $( "div#login input#password").hide();
    $( "div#login input#password_2").show(); 
    
    /* Login form */
	$("#login form").labeliseForm();
	/* Search form */
	$("#lpSearch #search-form2").labeliseForm();
	$("#lpSearch #search-form3").labeliseForm();
    
    /* Feature Accordion */
    equalHeight( $("#minifeatures div.mf_inner:even") );
    equalHeight( $("#minifeatures div.mf_inner:odd") );
    
    equalHeight( $("div.features" ).children().not( "div.break" ) );
    
    /* Make the left and main column the same length and do this for the frontpage only. */
    if ( $( "body" ).attr( 'class' ) == "node_id_66" ) {
        equalHeight( $( "#outer" ).children() );

        /* IE6 Fix: Make sure the empty div used to clear the floating is now 
        calcluated as part of the height. */
        var leftPanel = $( "#leftPanel" );
        leftPanel.height( leftPanel.height() - $( "#empty" ).height() );
    };
    
    
    $( "div#login input#password_2").focus( function() {
         $( "div#login input#password_2").hide();
         $( "div#login input#password").show();        
         $( "div#login input#password").focus();
     });

     $( "div#login input#password").blur( function() {
 		label_id = $(this).attr( "id" );
 		label = $( "#label_" + label_id ).text();

 		if ( $(this).attr('value') == label )
 		{
             $( "div#login input#password_2" ).show();            
 			$( "div#login input#password_2" ).attr( 'value', label );
             $(this).hide();
 		}
     });
}

function runOnLoad(f) {
    if (runOnLoad.loaded) f();    // If already loaded, just invoke f() now.
    else runOnLoad.funcs.push(f); // Otherwise, store it for later
}

runOnLoad.funcs = [adjustHeights]; // The array of functions to call when the document loads
runOnLoad.loaded = false; // The functions have not been run yet.

// Run all registered functions in the order in which they were registered.
// It is safe to call runOnLoad.run() more than once: invocations after the
// first do nothing. It is safe for an initialization function to call
// runOnLoad() to register another function.
runOnLoad.run = function() {
    if (runOnLoad.loaded) return;  // If we've already run, do nothing

    for(var i = 0; i < runOnLoad.funcs.length; i++) {
        try { runOnLoad.funcs[i](); }
        catch(e) { /* An exception in one function shouldn't stop the rest */ }
    }
    
    runOnLoad.loaded = true; // Remember that we've already run once.
    delete runOnLoad.funcs;  // But don't remember the functions themselves.
    delete runOnLoad.run;    // And forget about this function too!
};

// Register runOnLoad.run() as the onload event handler for the window
if (window.addEventListener)
    window.addEventListener("load", runOnLoad.run, false);
else if (window.attachEvent) window.attachEvent("onload", runOnLoad.run);
else window.onload = runOnLoad.run;

