$(function(){
	
	$('#colContent.landing .colMain').bigClick();	
	$('#colContent h1').not('.contentBody h1, .contentHeader h1').wrap('<div class="headerTag"></div>');
	
	$('.tocWrapper .selectChange').change(function(){
		var anchor = $(this).val();
		window.location = anchor;
	})
	
	// if the font size is already declared, then set it for all pages
	var knightFontSize = getCookie('knightFontSize');
	if(knightFontSize) {
		$('#colContent .colMain').css('font-size', knightFontSize);
	}

	$('.fontSizeOptions a.fontSize').click(function(){
		
		var size = $(this).attr('rel');
		var newSize = '';
		
		switch(size){
			case 's':
				newSize = '1em'
			break;
			case 'm':
				newSize = '1.2em'
			break;
			case 'l':
				newSize = '1.4em'
			break;
		}
		$('.colMain').css('font-size', newSize);
		setCookie('knightFontSize', newSize);
		return false;
	});
	
	$('#colContent table.data').tableHover({rowClass: 'hoverRow', colClass: 'hoverCol', cellClass: 'hoverCell', clickClass: 'click', ignoreCols: [1]}); 
	
	// var lineNumbers = '';
	// for(var i=0; i<=2500; i++) {
	// 	lineNumbers = lineNumbers + i + '<br />';
	// }
	// $('#colContent.statements .contentBody').prepend('<div class="lineNumbers">'+ lineNumbers+ '</div>');
    
    //set up image swap for graphs page
    $("#colContent .graphsContentNav li").click(function () {
        $("#consolidatedNav").children("li").removeClass("active");
        $("#glblMarketsNav").children("li").removeClass("active");
        $(this).toggleClass("active");
        
        var newSource;
        if ($(this).hasClass("total-revenues")) {
            newSource = "assets/images/content/graphs_totalrevenues.png"			 
        } else if ($(this).hasClass("pretax-margins")) {
            newSource = "assets/images/content/graphs_pretaxmargins.png"			 
        } else if ($(this).hasClass("diluted-eps")) {
            newSource = "assets/images/content/graphs_dilutedeps.png"			 
        } else if ($(this).hasClass("pretax-income")) {
            newSource = "assets/images/content/graphs_pretaxincome.png"			 
        } else if ($(this).hasClass("net-income")) {
            newSource = "assets/images/content/graphs_netincome.png"			 
        } else if ($(this).hasClass("glbl-markets-revenues")) {
            newSource = "assets/images/content/graphs_glblmrktsrevenues.png"			 
        } else if ($(this).hasClass("glbl-markets-pretax-income")) {
            newSource = "assets/images/content/graphs_glblmrktspretaxincome.png"
        } else if ($(this).hasClass("electronics-as-percent")) {
            newSource = "assets/images/content/graphs_electronicaspercent.png"
        } 
        $("#mainGraphsImage").attr("src", newSource);
        
        return false;
    });
    
    
    
    //set up image swap for global-markets page
    $("#global-markets-header").click(function () {
        var newSource;
        if ($(this).hasClass("active")) {
            newSource = "assets/images/content/headers/header-global-markets-main1.jpg"			 
        } else {
            newSource = "assets/images/content/headers/header-global-markets-main2.jpg"			 
        }
        $("#global-markets-header-image").attr("src", newSource);
        
        $(this).toggleClass("active");
		$(this).css('cursor', 'pointer');
        
        return false;
    });





	// Get the width of the paren and percent characters just once
	// to be used later. Don't need to calculate this for each found obj
	// var parens = $('<span>)</span>').hide();
	// 	$(parens).insertAfter('body');
	// 	var parensWidth = parens.width();
	// 	
	// 	var percent = $('<span>%</span>').hide();
	// 	$(percent).insertAfter('body');
	// 	var percentWidth = percent.width();
	// 	
	// 	var character = $('<span>$</span><br />').hide();
	// 	$(character).insertAfter('body');
	// 	var characterWidth = character.width();
	
	
	// if ( ($.browser.msie && $.browser.version > 7) )
	// {
		// $('body').append('<span id="parensWidth">)</span>');
		// var parensWidth = $('#parensWidth').width();
		// 	
		// $('body').append('<span id="percentWidth">%</span>');
		// var percentWidth = $('#percentWidth').width();
		// 	
		// $('body').append('<span id="characterWidth">$</span>');
		// var characterWidth = $('#characterWidth').width();
		// 	
		// $('body').append('<span id="zeroWidth">M</span>');
		// var zeroWidth = $('#zeroWidth').width();
		// 
		// $('#colContent table.data').spaceCharacter({
		// 	character: '$', 
		// 	selector: 'tbody > tr > td', 
		// 	exclude: ':first-child',
		// 	parensWidth: parensWidth,
		// 	percentWidth: percentWidth,
		// 	characterWidth: characterWidth,
		// 	zeroWidth: zeroWidth
		// });
	//}
	
	
	if ( $.browser.msie && $.browser.version < 8 ) // || !$.browser.msie 
	{
		$('.data > tbody > tr:first-child').addClass('tr-first');
		$('.data > tbody > tr:last-child, .data > thead > tr:last-child').addClass('tr-last');
		$('.data > tbody > tr > td:first-child').addClass('first-child');
	}
	
});


jQuery.fn.spaceCharacter = function(options) 
{
	var settings = {
		character : false,
		selector : false,
		exclude : false,
		offset : false,
		parensWidth: false,
		percentWidth: false,
		characterWidth: false,
		zeroWidth: false
    }
	
	if(options) {
        jQuery.extend(settings, options);
    };

	var parensWidth = options.parensWidth;
	var percentWidth = options.percentWidth;
	var characterWidth = options.characterWidth;
	var zeroWidth = options.zeroWidth;

	this.each(function(i){
		
		var maxWidth = 0;
		var totalWidth = 0;
		
		var collection = $(this).find(options.selector).not(options.exclude).each(function(j){
			$(this).children('.characterWrap').each(function(){
				var text = $(this).text();
				var num = text.length;
				var parens = 0;
				var percent = 0;
				var offset = 0;
				var cleanWidth = 0;
				var textClean = '';
				var character = options.character;
				var right = 0;
				
				if(text.indexOf(character) != -1) 
				{
					totalWidth = $(this).width() - characterWidth;
				} 
				else
				{
					totalWidth = $(this).width();
				}
				
				totalWidth = totalWidth + characterWidth + 1;

				// offset is used b/c the characterWrap is given a neg right margin with the following two classes
				// so the decimals/commas vertically align properly in the table columns. This offset pulls the
				// character back to the left where it should be.				
				if( $(this).parents('td').hasClass('parens') )
				{
					offset = parensWidth;
				}
				
				if( $(this).parents('td').hasClass('percent') )
				{
					offset = offset + percentWidth;
				}
				
				// if the new totalWidth is greater than previously defined, set it as the new totalWidth
				if( totalWidth > maxWidth )
				{
					maxWidth = totalWidth;
				}
				
				if( $(this).parents('td').eq(0).hasClass('parens') || $(this).parents('td').eq(0).hasClass('percent') )
				{
					$(this).children('.character').css('margin-left', '-'+ offset +'px');
				}
			});
		});	
		
		collection.children('.characterWrap').css({
			'width': maxWidth
		});
		
	});
}


var getCookie = function(name){  
	var re=new RegExp(name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1]; //return its value
	return null;
};

var setCookie = function(name, value){
	document.cookie = name + "=" + value + "; path=/";
};


jQuery.fn.perfectForm = function(options)
{
	var settings = {
    	overlap: true				
    }

    if(options) {
        jQuery.extend(settings, options);
    };

	this.each(function(){
		var input = $(this).next('input');
		var label = $(this);
		
		// first check all inputs for values, then hide it's label if it has a value
		if( settings.overlap ) {
			label.addClass('overlap');
		}
		
		if( settings.overlap && input.val() != '' ) {
			label.hide();
		}
		
		label.click(function(){
			label.hide();
			input.focus();
		}, function(){
			if( input.val() == '' ) {
				label.show();
			}
		});
		
		// then add a focus event to all inputs to hide their labels when focused on, 
		// and remain hidden on blur if a value is entered
		input.focus(function(){
			label.hide();
		}).blur(function(){
			if( $(this).val() == '' ) {
				label.show();
			}
		});
		
		// do the same thing for elements added to the DOM after page load. jQuery 1.3 has the
		// 'live' method, but doesn't support focus or blur yet, so use livequery for now.
		input.livequery('focus', function(){
			label.hide();
		}).livequery('blur', function(){
			if( $(this).val() == '' ) {
				label.show();
			}
		});
	});
}

jQuery.fn.bigClick = function(options)
{
	var settings = {
		cssClass : 'clickable'
    }
	
	if(options) {
        jQuery.extend(settings, options);
    };
	
	this.each(function(){
		var anchor = $(this).find('a')[0];
		
		if(!anchor)
			return;			
		
		var href = $(anchor).attr('href');
		var title = $(anchor).attr('title');
		
		$(this).attr('title', title);
		
		$(this).mouseover(function(){
			$(this).css('cursor', 'pointer');
		});
		
		$(this).addClass(settings.cssClass).click(function(){
			window.location = href;
		});
	});
}		

jQuery.fn.autoWidth = function(options) 
{
    var settings = {
    	minWidth   : false,
        limitWidth  : false,
        ignore	: ''
    }

    if(options) {
        jQuery.extend(settings, options);
    };

    var maxWidth = 0;

	this.not(settings.ignore).each(function(){
        if ($(this).width() > maxWidth){
        	if(settings.limitWidth && maxWidth >= settings.limitWidth) {
        		maxWidth = settings.limitWidth;
        	} 
        	else if(settings.minWidth && maxWidth <= settings.limitWidth)
        	{
        		maxWidth = settings.minWidth;
        	} 
        	else 
        	{
        		maxWidth = $(this).width();
        	}
        }
	});	 

	this.not(settings.ignore).width(maxWidth);
}


jQuery.fn.listHandlers = function(events, outputFunction) {
    return this.each(function(i){
        var elem = this,
            dEvents = $(this).data('events');
        if (!dEvents) {return;}
        $.each(dEvents, function(name, handler){
            if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
               $.each(handler, function(i,handler){
                   outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
               });
           }
        });
    });
};




