// ==============================
// SET VARIABLES
// ==============================


function highlightSectionAndPages(urlParts){
	
	//break urlParts.pathParts into an array
	var arrayPieces = urlParts.pathParts;
	//var fullPath = '/'+arrayPieces[1]+'/'+arrayPieces[2]+'/'+arrayPieces[3];
	//alert('/'+arrayPieces[1]+'/'+arrayPieces[2]+'/'+arrayPieces[3]);
	var fullPath = '';
	var numOfArrayPieces = arrayPieces.length;
	
	for (var i=1; i<numOfArrayPieces; i++){
		fullPath += '/' + arrayPieces[i];
	}
	
	//Now evaluate each <A> under li.on and see if their HREF values are equal to the page requested
	//If they are, assign 'highlightMe' to that LI and its parents under li.on
	$('li.on').find('a').each(function(){
		
		if ($(this).attr('href') == fullPath){
			$(this).parents('li.on li').addClass('highlightMe');
		}
	});	
}

// Returns an object that contains the active main and left nav IDs based on the url.
function activeNavID(urlParts) {
	var output = new Object();
	output.mainID = null;
	output.subID = null;
	// Check the first URL directory after "/network/"
	
	switch (urlParts.pathParts[2]) {
		case 'neighborworksProgs':
			output.header = '#primaryNav li.n1 span.subnavHeading';
			output.mainID = '#primaryNav li.n1 a';;
			output.subID = '.inThisSection li.n1';
			break;
		case 'training':
			output.header = '#primaryNav li.n2 span.subnavHeading';
			output.mainID = '#primaryNav li.n2 a';
			output.subID = '.inThisSection li.n2';
			break;
		case 'foreclosure':
			output.header = '#primaryNav li.n3 span.subnavHeading';
			output.mainID = '#primaryNav li.n3 a';
			output.subID = '.inThisSection li.n3';
			break;
		
		case 'pubs':
		case 'newsroom':
			output.header = '#primaryNav li.n4 span.subnavHeading';
			output.mainID = '#primaryNav li.n4 a';
			output.subID = '.inThisSection li.n4';
			break;
		case 'aboutUs':
			output.header = '#primaryNav li.n5 span.subnavHeading';
			output.mainID = '#primaryNav li.n5 a';
			output.subID = '.inThisSection li.n5';
			break;
		case 'nonprofits':
			output.header = '#primaryNav li.n6 span.subnavHeading';
			output.mainID = '#primaryNav li.n6 a';
			output.subID = '.inThisSection li.n6';
			break;
		case 'donors':
			output.header = '#primaryNav li.n7 span.subnavHeading';
			output.mainID = '#primaryNav li.n7 a';
			output.subID = '.inThisSection li.n7';
			break;
		case 'consumers':
			output.header = '#primaryNav li.n8 span.subnavHeading';
			output.mainID = '#primaryNav li.n8 a';
			output.subID = '.inThisSection li.n8';
			break;
		default:
			output.mainID = null;
	}
	return output;
}

function randomRange(minNum,maxNum) {
	var randomnumber=Math.floor(Math.random() * (maxNum - 1 + minNum)) + minNum;
	return randomnumber;
}




// ==============================
// RUN ALL ONLOAD JQUERY COMMANDS
// ==============================
$(document).ready(function() {
	if (jQuery.browser.msie && (jQuery.browser.version == '6.0' || jQuery.browser.version == '7.0')) {
		$('div#primaryNav > ul > li').mouseover(function() {
			 $(this).children('ul').css({left:'auto'});
		});
		$('div#primaryNav > ul > li').mouseout(function() {
			 $(this).children('ul').css({left:'-9999em'});
		});
	}
	// MAIN NAV ON STATE
	// Process the URL, the parseURL() function is in urlFunctions.js
	var urlParts = parseURL();
	var navID = activeNavID(urlParts);

	$(navID.mainID).addClass('on');
	$(navID.subID).addClass('on');
	
	var navHeader = $(navID.subID).children('h2.subnavHeading').html();
	if (navHeader != ''){
		$('div#rightSection div.inThisSection h2').html( $(navID.subID).children('h2.subnavHeading').html() );
	} else {
		$('div#rightSection div.inThisSection h2').html( $(navID.mainId + '>strong').html() );
	}
	highlightSectionAndPages(urlParts);	



	// ==============================
	// FONT SIZE BUTTONS
	// ==============================
	$('.increaseSize').mousedown(function() {
		var currentFontSize = parseInt($('body').css('font-size'), 10);
		var newFontSize = currentFontSize + 1;
		$('body').css('font-size',newFontSize);
	});
	$('.decreaseSize').mousedown(function() {
		var currentFontSize = parseInt($('body').css('font-size'), 10);
		var newFontSize = currentFontSize - 1;
		$('body').css('font-size',newFontSize);
	});


	// ========================================================
	// ALTERNATING TABLE ROWS
	// ========================================================	
	$('table.table-organizations tr:has(td):odd').addClass('rowEven');
	//});

	
	
	//	==================
	//	PARTNER PAGE
	//	==================
	// First row
	/*$('div.threeColGrid table tr:eq(0)').addClass('firstRow');
	
	// Column one and three
	$('div.threeColGrid table tr').each(function() {
		$(this).find('td:eq(0)').addClass('one');
		$(this).find('td:eq(2)').addClass('three');
	});
	
	
	// Empty cells
	$('div.threeColGrid td:emtpy').addClass('empty');*/
	
	//	==============================
	//	HOME PAGE SLIDESHOW
		// Wrapped in a conditional to skip all of this code on all but the home page.
	//	==============================
	if (typeof(homeSlideShowPresent) != 'undefined') {
		var currentHomeSlide = 0;
		var homeSlidefadeDelay = 10000;
	// Initialize the first slide.
	$('#homeSlideshow .slide .pic').hide();
	$('#homeSlideshow .slide .right').hide();
	$('#homeSlideshow .slide:eq(0) .pic').show();
	$('#homeSlideshow .slide:eq(0) .right').show();
	// Create the controls
	var totalSlides = $('#homeSlideshow .slide').size();
    $('div#slideshowControls ul').append('<li class="leftArrow"></li>');
    $('div#slideshowControls ul').append('<li class="pause"></li>');
	for (i=1; i<=totalSlides; i++) {
		$('div#slideshowControls ul').append('<li class="link"' + ' ref="' + (i - 1) + '">' + i + '</li>');
	}
    $('div#slideshowControls ul').append('<li class="rightArrow"></li>');
	// Initialize the on state
	$('#slideshowControls ul li:eq(2)').addClass('on');
	// Position the controls.
		var slideShowULWidth = 0;
		$('#slideshowControls ul li').each(function() {	
			slideShowULWidth += $(this).outerWidth();
			//alert($(this).outerWidth());
		});
		slideShowULWidth += 2;
		$('#slideshowControls').width(slideShowULWidth);
		var newLeftMargin = 703 + ((240 - slideShowULWidth)/2);
		//alert (newLeftMargin.toString() + 'px');
		$('#slideshowControls').css('margin-left',newLeftMargin);
	}
	
	/*$('#slideshowControls div').mouseover(function() {
		$(this).addClass('hover');					
	});
	$('#slideshowControls div').mouseout(function() {
		$(this).removeClass('hover');					
	});*/
	$('#slideshowControls li.pause').click(function() {
		$(document).stopTime('homeSlideshow');
		$(document).stopTime('homeSlideshowBackword');
		$(document).stopTime('homeSlideshowForward');
		$(this).css({
			'background-position':'-20px'
		});
	});
	$('#slideshowControls li.link').click(function() {
		$(document).stopTime('homeSlideshow');
		transitionHomeSlide($(this).attr('ref'), 'manual');					
	});
	function transitionHomeSlide(slide, dir) {
		var fadeDuration = 750;
		if (dir == 'forward') {
			if (currentHomeSlide == (totalSlides - 1)) {
				slide = 0;
			} else {
				slide = parseInt(currentHomeSlide, 10) + 1;
			}
		} else if (dir == 'back') {
			if (currentHomeSlide == 0) {
				slide = totalSlides - 1;
			} else {
				slide = parseInt(currentHomeSlide, 10) - 1;
			}
		}
		
		//alert('old: ' + currentHomeSlide + ', next: ' + slide);
		// Switch the on state on the controls
		$('#slideshowControls li.link').removeClass('on');
		$('#slideshowControls li.link:eq(' + slide + ')').addClass('on');
		
		// Hide the new image before fading it in.
		$('div#homeSlideshow .slide:eq(' + slide + ' ) .pic').hide();
		// Fade out the old slide
		$('div#homeSlideshow .slide:eq(' + currentHomeSlide + ') .pic').fadeOut(fadeDuration);
		// Fadein in the new slide, slide the new slate in, bring the controls back.
		$('div#homeSlideshow .slide:eq(' + slide + ') .pic').fadeIn(fadeDuration, function () {
			// Hide all slates
			$('div#homeSlideshow .slide .right').hide();
			// Reveal the new slate
			$('div#homeSlideshow .slide:eq(' + slide + ') .right').show();
		});
		// set the new slide as the current slide, for fading out on the next iteration.
		currentHomeSlide = slide;
	}
	
	
	$('#slideshowControls li.rightArrow').click(function() {
		$(document).stopTime('homeSlideshow');
		$(document).stopTime('homeSlideshowBackword');
		$(document).oneTime(100, 'homeSlideshowOneoff', function(i) {
 			transitionHomeSlide(-1, 'forward');
		}, 0);
		$(document).everyTime(homeSlidefadeDelay, 'homeSlideshowForward', function(i) {
 			transitionHomeSlide(-1, 'forward');
		}, 0);
		$('#slideshowControls li.pause').css({'background-position':'0px'});
	});
	$('#slideshowControls li.leftArrow').click(function() {
		$(document).stopTime('homeSlideshow');
		$(document).stopTime('homeSlideshowForward');
		$(document).oneTime(100, 'homeSlideshowOneoff', function(i) {
 			transitionHomeSlide(-1, 'back');
		}, 0);
		$(document).everyTime(homeSlidefadeDelay, 'homeSlideshowBackword', function(i) {
 			transitionHomeSlide(-1, 'back');
		}, 0);	
		$('#slideshowControls li.pause').css({'background-position':'0px'});			
	});
	// Set the autoloop. This is canceled once a button is clicked.
	// The jquery.timers plugin throws a non-supported method error, it doesn't appear to break the functionality.
	// But it will break any jQuery that follows, so this must be the last set of code.
	if ($('#homeSlideshow .slide').size() > 1) {
		$(document).everyTime(homeSlidefadeDelay, 'homeSlideshow', function(i) {
 			transitionHomeSlide(-1, 'forward');
		}, 0);
	} else {
		$('#slideshowControls').hide();
	}
	
	
		
	
/* Image Slider functions */
	var $sliderButtonLeft,
		$sliderButtonRight,
		$sliderImageFrame,
		slidesPerScreen = 1.177,
		slidesPerScroll = 1.177,
		startPosition = 0,
		newLeftPosition = 0,
		scrollDistance = 0,
		widthOfVisibleArea = 0,
		widthOfSlides = 0;

	function nw_movePics(e){
		
		//turn off clickability while the scroll is in effect
		$('div.slider-nav img').unbind('click', nw_movePics);
		
		if (e.data.direction == 'left'){ newLeftPosition = parseInt($sliderImageFrame.css('left'), 10) + scrollDistance; }
		else if (e.data.direction == 'right'){ newLeftPosition = parseInt($sliderImageFrame.css('left'), 10) - scrollDistance; }
		
		$sliderImageFrame.animate({left: newLeftPosition + 'px'}, 300, nw_highlightNavArrows());
	}
	
	function nw_highlightNavArrows(){
		
		$sliderButtonLeft.bind('click', {direction: 'left'}, nw_movePics);
		$sliderButtonRight.bind('click', {direction: 'right'}, nw_movePics);
		$('div.slider-nav img').removeClass('unhighlightNavArrow');
		
		/*
		alert('new left: ' + newLeftPosition + "\n" +
			'start position: ' + startPosition + "\n" +
			'width of slides: ' + widthOfSlides + "\n" +
			'width of visible: ' + widthOfVisibleArea + "\n");
		*/
		//if ( widthOfSlides > Math.abs(newLeftPosition) + startPosition + widthOfVisibleArea){
		if ( newLeftPosition >= 0 ){
			$sliderButtonLeft.unbind('click', nw_movePics);
			$sliderButtonLeft.addClass('unhighlightNavArrow');
		} else if ( (widthOfSlides + newLeftPosition) < widthOfVisibleArea){
		//} else if (newLeftPosition + widthOfSlides  > -10 ){
			$sliderButtonRight.unbind('click', nw_movePics);
			$sliderButtonRight.addClass('unhighlightNavArrow');
		}
	}

/* end image slider functions */

	//The following is for the image slider
	$sliderButtonLeft = $('div#slider-button-left img');
	$sliderButtonRight = $('div#slider-button-right img');
	$sliderImageFrame = $('div#slider-master div#slider-image-frame');
	
	if ($sliderImageFrame.css('left') == 'auto'){
		$('#training-slider').css('display', 'none');	
	}
	
	
	$firstSlide = $sliderImageFrame.children(1);

	//Set width of div#slider-image-frame. Loop through slides and tally their widths and margins.
	$sliderImageFrame.children('div.slider-image:last-child').css('margin-right', 0);

	$sliderImageFrame.children('div.slider-image').each(function(){
		widthOfSlides += parseInt($(this).css('width'), 10);
		widthOfSlides += parseInt($(this).css('padding-left'), 10);
		widthOfSlides += parseInt($(this).css('padding-right'), 10);
		//Now, set the height of the slider holder according to the largest single slide height
		//Adding up the height of each component in the slider-image gives better results than
		//using the height of the slider-image div itself.
		
		var newHeight = $('img', this).innerHeight() + $('p', this).innerHeight();
				
		if ( newHeight > $('div#slider-master').outerHeight() - 50 ){
			$('div#slider-master').css('height', 50 + newHeight + 'px');
		}
		
	});
		
	//Set the width of the image slider frame so the images all appear in one row
	$sliderImageFrame.css('width', widthOfSlides);
	
	//The difference here is that newLeftPosition will change as the slider is moved.
	//startPosition will remember the initial offset value of the sliding frame
	newLeftPosition = startPosition = 0; //parseInt($sliderImageFrame.css('left'), 10);
		
	scrollDistance = slidesPerScroll * (parseInt($firstSlide.css('width'), 10) + parseInt($firstSlide.css('margin-right'), 10));
	widthOfVisibleArea = slidesPerScreen * parseInt($firstSlide.css('width'), 10) + (slidesPerScreen - 1) * parseInt($firstSlide.css('margin-right'), 10);
	
	scrollDistance = Math.round(scrollDistance);
	widthOfVisibleArea = Math.round(widthOfVisibleArea);
	
	
	nw_highlightNavArrows();
	//end image slider
	
	
	
	//	===================
	//	CONNECT WITH US BOX
	//	Forces the component box to the bottom of the right margin. If it's not there already.
	//	===================
	var currentURL = parseURL();
	var connectWithUsHeight =  $('div#rightSection .connect').outerHeight();
	var otherRightMarginContent = $('div#rightSection').outerHeight() - connectWithUsHeight;
	// 28 pixels is added to account for the bottom of the nav and some extra for different browser renderings.
	var mainBodyHeight = $('div#mainBody').outerHeight() + 28;
	// If we're on the home page, we have to subtract the height of the slideshow.
	if (currentURL.pathFile == '/network/' ||currentURL.pathFile == '/network/index.asp') {
		mainBodyHeight -= 356;
		otherRightMarginContent -= 20;
	}

		// if the height of all the right margin content is less the the main body height, reposition the box.
	if ((connectWithUsHeight + otherRightMarginContent) < mainBodyHeight) {
		var connectWithUsTopMargin = mainBodyHeight - (connectWithUsHeight + otherRightMarginContent);
		
		if ($('#training-slider') && $('#training-slider').css('display') != 'none'){
			connectWithUsTopMargin += ( 0.1 * $('#training-slider').innerHeight() );
		}
		
		$('div#rightSection .connect').css('margin-top',connectWithUsTopMargin);
	}
});
