// remap jQuery to $
(function($){

// ####################################
// speed detection script
// ####################################
var SpeedTest = function() {
  /*
  From:  http://techallica.com/kilo-bytes-per-second-vs-kilo-bits-per-second-kbps-vs-kbps/
  256 kbps            31.3 KBps
  384 kbps            46.9 KBps
  512 kbps            62.5 KBps
  768 kbps            93.8 KBps
  1 mbps ~ 1000kbps   122.1 KBps
  */
};
SpeedTest.prototype = {
  runCount: 3                 // how many times we want to run the test for
  ,imgUrl: "/img/misc/speedtest.png"    // Where the image is located at
  ,size: 5484                // bytes
  ,run: function( options ) {
    this.results = []; // reset the results
    this.callback = ( options && options.onEnd ) ? options.onEnd : null;
    this.runTrial(0, options);
  }

  ,runTrial: function(i, options ) {
    var imgUrl = this.imgUrl + "?r=" + Math.random();
    var me = this;
    var testImage = new Image();
    testImage.onload = function() {
      me.results[i].endTime = ( new Date() ).getTime();
      me.results[i].runTime = me.results[i].endTime - me.results[i].startTime;

      if ( i < me.runCount - 1 )
        me.runTrial( i + 1 ); // run the next trial
      else
      {
        // Execute the callback
        if( me.callback )
          me.callback( me.getResults() );
      }
    };
    this.results[i] = { startTime: ( new Date() ).getTime() };
    testImage.src = imgUrl;
  }

  ,getResults: function() {
    var totalRunTime = 0;
    for( var i = 0; i < this.runCount; i++ )
    {
      if( !this.results || !this.results[i].endTime )
        return null; // exit if we found no endTime.  --> test’s not done yet
      else
        totalRunTime += this.results[i].runTime;
    }

    var avgRunTime = totalRunTime / this.runCount;

    return {
      avgRunTime: avgRunTime
      ,Kbps: ( this.size * 8 / 1024 / ( avgRunTime / 1000 ) )
      ,KBps: ( this.size / 1024 / ( avgRunTime / 1000 ) )
    };
  }
}

// ------------------------------------




// ####################################
// debugging JS calls
// ####################################

var debug = false;

if(debug == true) {
	$('body').prepend('<div id="error" style="left:200px"></div>');
}

// ------------------------------------


// ####################################
// AJAX - setup
// ####################################

$.ajaxSetup ({
	cache: false
});

var ajax_load = '<img src="img/misc/loader.gif" alt="loading..." class="ajaxload" />';

// ------------------------------------


// ####################################
// Page Load - setup
// ####################################

var bgImgShow = false;
var staticOverride = false;
var fullOverride = false;
var vidHTML = $('#videoContainer').html();

$(document).ready(function () {
	
	/* Flash Detection */
	if(!FlashDetect.installed){
		
		$('#videoContainer').remove();
		bgImgShow = true;
		
		//$('#full').show();
		
		startPage();
		
	} else {
	
		/* Call speed detection script */
		var st = new SpeedTest();
		
		st.run({
		  onStart: function() {
		    //alert('Before Running Speed Test');
		  },
		  onEnd: function(speed) {
		    //alert( 'Speed test complete:  ' + speed.Kbps + ' Kbps');
		    // put your logic here
		    if( speed.Kbps < 300 ) {
			    $('#videoContainer').remove();
			    bgImgShow = true;
			    
			    $('#full').show();
		    	//alert('Your connection is too slow');
		    } else {
		    	$('#static').show();
		    }
		    
		    startPage();
		   	
		  }
		});		
	}	
});

// ------------------------------------


// ####################################
// Static/Full site buttons
// ####################################

function startPage() { if(debug == true){ $('#error').append('<div>startPage</div>'); }
	
	if(fullOverride) {
		//alert('here')
		$('body').prepend('<div id="videoContainer" class="videoContainer">'+vidHTML+'</div>');
		$('.bg_img img').hide();
		
		navLinks('index.php', 'Home', '');
		
	} else if(staticOverride) {
		//alert('here')
		$('#videoContainer').remove();
		$('.bg_img img').show();
		
		navLinks('index.php', 'Home', '');
	} else if(window.location.href.indexOf('.php') != -1) {
		
		if(window.location.href.indexOf('index.php') != -1) {
		    window.location.href = '/#/home'; 
		} else if(window.location.href.indexOf('about.php') != -1) {
		    window.location.href = '/#/about';
		} else if(window.location.href.indexOf('strategy.php') != -1) {
		    window.location.href = '/#/approach';
		} else if(window.location.href.indexOf('news.php') != -1) {
		    window.location.href = '/#/news';
		} else if(window.location.href.indexOf('companies.php') != -1) {
		    window.location.href = '/#/companies';
		} else if(window.location.href.indexOf('contact.php') != -1) {
		    window.location.href = '/#/contact';
		}
		
	} else if(window.location.hash == '' || window.location.hash == '#/home') {
		window.location.href = '/#/home';
		
		setNav();
		setUpPage();
		
	} else {
		tHash = window.location.hash;
		tlength = tHash.length;
		tpos = tHash.indexOf("#", 0) + 2;
		tpos2 = tHash.indexOf('/',tpos); 
		if(tpos2 != -1) {
		    loadText = tHash.substring(tpos,tpos2);
		    subText = tHash.substring(tpos2,tlength);
		} else {
		    loadText = tHash.substring(tpos,tlength);
		    subText = '';
		    
		}
		loadURL = loadText + '.php';
		
		if(loadURL == 'approach.php') {
		    loadURL = 'strategy.php'
		}
		
		navLinks(loadURL, loadText, subText);
	}
	
	whichMovie(window.location.hash);
	
	//movieplayer.gotoMovie(movie/*, 0*/);

}
// ------------------------------------


// ####################################
// Static/Full site buttons
// ####################################

	$('#static').click(function(event) {
		event.preventDefault();
		
		bgImgShow = false;
		staticOverride = true;
		fullOverride = false;
		
		$('#static').hide();
		$('#full').show();
		
		startPage()
	});
	
	$('#full').click(function(event) {
		event.preventDefault();
		
		bgImgShow = true;
		fullOverride = true;
		staticOverride = false;
		
		$('#full').hide();
		$('#static').show();
		
		startPage();
	});

// ------------------------------------


// ####################################
// Which Movie?
// ####################################

var movie = 1;
//var cuepoint = 0;
var updateMovie = false;

function whichMovie(currentPage) { if(debug == true){ $('#error').append('<div>whichMovie</div>'); }

	//alert(bgImgShow)
	//alert('fullOverride= '+fullOverride)
	if(!staticOverride) {
		if(!bgImgShow || fullOverride) { // if passed flash/speed detection
	
			//alert(movie+' and '+cuepoint);
		
			if(currentPage.indexOf('about') != -1) {
				if(movie != 2 /*|| cuepoint != 2*/) {
					movie = 2;	
					//cuepoint = 2;
					updateMovie = true;
				} else {
					updateMovie = false;
				}
			} else if(currentPage.indexOf('strategy') != -1) {
				if(movie != 3 /*|| cuepoint != 2*/) {
					movie = 3;
					//cuepoint = 2;
					updateMovie = true;
				} else {
					updateMovie = false;
				}
			}else if(currentPage.indexOf('companies') != -1) {
				if(movie != 3 /*|| cuepoint != 2*/) {
					movie = 3;	
					//cuepoint = 2;
					updateMovie = true;
				} else {
					updateMovie = false;
				}
			} else if(currentPage.indexOf('contact') != -1) {
				if(movie != 4 /*|| cuepoint != 2*/) {
					movie = 4;	
					//cuepoint = 2;
					updateMovie = true;
				} else {
					updateMovie = false;
				}
			} else {
				if(movie != 1 /*|| cuepoint != 0*/) {
					movie = 1;
					//cuepoint = 0;
					updateMovie = true;
				} else {
					updateMovie = false;
				}
			}
			
			var movieplayer = document.movieplayer;
			//alert(movie+' and '+cuepoint);
			//alert(updateMovie)
			if(updateMovie == true) {
				movieplayer.gotoMovie(movie);
			}
		
		}
	}
	
}

// ------------------------------------


// ####################################
// Primary Navigation - setup for AJAX
// ####################################

function setNav() { if(debug == true){ $('#error').append('<div>setNav</div>'); }
	//alert('here')
	$('#nav a.primary').each(function(){
		
		$(this).click(function(event){
			event.preventDefault();
			
			whichMovie($(this).attr('href'));
			
			loadURL = $(this).attr('href');
			loadText= $(this).text();
			
			navLinks(loadURL, loadText, '');
		    
		});
			
	});
}

/*$("#error").ajaxSuccess(function(evt, request, settings){
      $(this).append("<li>Successful Request!</li>");
      });*/

navLinks = function (loadURL, loadText, subText) {
	
	//alert(loadURL +' and '+loadText)
	
	$('#navContainer').append(ajax_load).load(loadURL + ' #nav', null, function(responseText, textStatus, req){
	   	
		if (textStatus == "error") {
			//alert(responseText);
			window.location.href(loadURL);
		}
	    			    
	   setNav();
	   
	   $('#ajaxContent').append(ajax_load).load(loadURL + ' #content', null, function(responseText, textStatus, req){ 
	       
	       if (textStatus == "error") {
	       	//alert(responseText);
	       	window.location.href(loadURL);
	       }
	       setUpPage();
	       
	       //$('html, body').animate({ scrollTop: 0 }, 500);
	       /**
	        * Hack by MS
	        */
	       if(window.location.href.indexOf('news') == -1)
		       scrollScreen('load');
	       
	   });
	   
	   if(subText.indexOf(loadText) != -1) {
	       subText = '';
	   }
	   	   
	   window.location.hash= '#/'+loadText.toLowerCase()+''+subText;
	   
	   return false;
	    
	});
	
}

// ------------------------------------


// ####################################
// Height Variables
// ####################################

// variables for the heights of certain page elements. These are used to position other elements
var vHeaderHeight = 84;
var vScrollerHeight = 29;

var vAvailableHeight = 0;
var vViewableIndex = 0;
var vViewableHeight = 0;
function getHeight() {
	//$('.section .bg_img').hide();
	vAvailableHeight = $(window).height() - vHeaderHeight - (vScrollerHeight)*2;
	//alert(vAvailableHeight)
	//$('.section .bg_img').show();
	//alert(vAvailableHeight)
	vViewableIndex = Math.floor(vAvailableHeight/125);
	vViewableHeight = vViewableIndex*125;
}

// ------------------------------------


// ####################################
// Page setup
// ####################################

function setUpPage() { if(debug == true){ $('#error').append('<div>setUpPage</div>'); }
	
	// set variable for which section the page is on
	var vScroll = '';
	
	if(vScroll == 'scroll') {
		scrollScreen('load');
	}
	
	if(window.location.hash == '#/home') {
		
		if(!navigator.userAgent.match(/iPad/i))
			setBGVideo();
		
		$('.homePromo').show();
		
		var homePadding = 0; 
		$('.homePromo').each(function(index) {
			if($(this).height()+homePadding <= 250) {
				$(this).height(250-homePadding); 
			} else if($(this).height()+homePadding <= 375) {
				$(this).height(375-homePadding); 
			} else if($(this).height()+homePadding <= 500) {
				$(this).height(500-homePadding); 
			} else if($(this).height()+homePadding <= 625) {
				$(this).height(625-homePadding); 
			} else if($(this).height()+homePadding <= 750) {
				$(this).height(750-homePadding); 
			}
		});
		
		setHomePromos();
			
		setContentPos(); // set position of the content
		
		if(!navigator.userAgent.match(/iPad/i)){
			setSubSections(); // Give ID to each subsection, generates the secondary nav and show/hides the scrollers
		
			//$('.videoContainer').height(vAvailableHeight);
		
			setBGImg();
		}else{
			setiPadBG();
		}
		// header link
		
		$('header a').click(function(event) {
			event.preventDefault();
			loadText = 'Home';
			loadURL = $(this).attr('href');
			
			navLinks(loadURL, loadText, '');
		});
		
	} else {
	// } else if(window.location.href.indexOf('news') == -1) {
		//For the news page we don't want either scrollers or the video in the bg
		setContentPos(); // set position of the content
		
		if(navigator.userAgent.match(/iPad/i)){
			setiPadBG();
			return true;
		}
		
		setPromos(); // Generates sub menus
		
		showHideScrollers('hide');
		
		setSubSections(); // Give ID to each subsection, generates the secondary nav and show/hides the scrollers
		
		setNewsStory();
			
		setBGVideo();
		
		setBGImg();
		
		if(vScroll == 'scroll') {
			scrollScreen('load');
		}
		
		$("#nav ul#secondary a[title]").tooltip({ position: "center left", effect:"fade"}); //jQuery Tools - Tooltips
		
		 //Event - clicks
		$('ul#secondary a, #promos a, a.readMore, .newsStory a, .scroller a').each(function() { // scroll the screen when we click on a link in the secondary nav
			$(this).click(function() {
			 	scrollScreen(this);
			});
		});
		
		$('a[href^="http://"]:not(a[href^="http://blackocean"],a[href^="http://www.blackocean"])').attr({
			target: "_blank", 
		  	title: "Opens in a new window"
		});
		
	}
	
//	$('#preloader div').click(function() { // skip preloader
//	
//		if($('html').hasClass('ie8') || $('html').hasClass('ie7') || $('html').hasClass('ie6')) {
//		   
//			$('object').get();
//		   
//		} else {
//			video = document.getElementById('video');
//			video.pause();
//			video.src = "";
//			video.load();
//		}
//		videoEnd();
//		$('#preloader').fadeOut();
//	});
	
} 

$(window).bind('orientationchange', function(e){
	setContentPos(); // set position of the content
	setiPadBG();
	
	if(window.location.href.indexOf('news') != -1)
		$('.news-bg').find('img').attr('height', $(window).height() - 142);
});

// Event - resize
$(window).resize(function() { // set scroller height onResize
	if(navigator.userAgent.match(/iPad/i))
		return true;
	 	
	setScrollerPos();
	setContentPos(); // set position of the content
	setBGImg();
	setBGVideo();
	
});

// Event - scroll
jQuery(window).bind('scrollstart', function(e){
    $('.tooltip').hide(); // hide tooltips
});
// Event - scroll
jQuery(window).bind('scrollstop', function(e){
	//TODO remove the 2 lines below as the event is unbound in script.js 
	if(navigator.userAgent.match(/iPad/i))
		return true;
	
	if(window.location.href.indexOf('news') == -1 )
    	setSecondaryNavCurrent('scroll');
    
    if(window.location.hash == '#/about/about') {
	   window.location.hash = '#/about';
	} else if(window.location.hash == '#/approach/approach') {
	  window.location.hash = '#/approach';
	} else if(window.location.hash == '#/companies/companies') {
	  window.location.hash = '#/companies';
	} else if(window.location.hash == '#/news/news') {
	  window.location.hash = '#/news';
	}
    	
});


function setHomePromos() { if(debug == true) { $('#error').append('<div>setHomePromos</div>'); }
	//homepage positioning of promos
	$('#main .homePromo:first').addClass('homePromoFirst');
	$('#main .homePromo:odd').addClass('homePromoOdd');
	$('#main .homePromo:first').css('background','url(/img/bg/opaque2.png)');
	
}

objWidth = 1280;
objHeight = 720;



function setBGVideo() { if(debug == true) { $('#error').append('<div>setBGImg</div>'); }
	
	$('.videoContainer').each(function() { 
	
		getHeight();
		
		screenWidth = $(window).width();
		screenHeight = vAvailableHeight;
		//alert('screenWidth='+screenWidth+' and '+'screenHeight='+screenHeight);
	
//		preWidth = $('#preloader').outerWidth();
//		preHeight = $('#preloader').outerHeight();
//		
//		preLeft = (screenWidth/2) - (preWidth/2) + 'px';
//		preTop = (screenHeight/2) - (preHeight/2) + vHeaderHeight + vScrollerHeight + 'px';
//		
//		$('#preloader').css('visibility','visible');
//		$('#preloader').css('left',preLeft);
//		$('#preloader').css('top',preTop);
		
		//$('footer').css('display','block');
		
		//videoLeft = (screenWidth/2) - (objWidth/2) + 'px';
		videoTop = vHeaderHeight + vScrollerHeight + 'px';
		
		$('.videoContainer').each(function(index) {
			$(this).css('top',videoTop);
			$('.videoContainer').height(screenHeight);
			$('.videoContainer').width(screenWidth);
		});
		
		//$('.videoContainer').css('visibility','visible');
		
		
		/*if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
			// do nothing
		} else {
			myVideo = document.getElementById('video');
			
			if(myVideo) {
			//alert('videostate= '+myVideo.readyState)
				//if (navigator.userAgent.indexOf("Firefox")!=-1) {
				//	myVideo.addEventListener('canplaythrough',myHandlerFF,false);
				//} else {
					myVideo.load()
					myVideo.addEventListener('progress',myHandlerWebkit,false);
				//}
			}
		}*/
		
	});

}

/*function myHandlerFF() {
//alert('videostate= '+myVideo.readyState)
	myVideo.play();
}/*

/*function myHandlerWebkit() {
	endBuf = myVideo.buffered.end(0);
	totalDuration = myVideo.duration;
	//$('#log').append(endBuf+' / '+totalDuration+' - ')
	if(endBuf >= (totalDuration-2)) {
		myVideo.play();
	}
}*/

function setNewsStory() { if(debug == true) { $('#error').append('<div>setNewsStory</div>'); }
	//homepage positioning of promos
	$('#main .newsStory:first').addClass('newsStoryFirst');
	$('#main .newsStory:odd').addClass('newsStoryOdd');
	
}

function setSubSections() { if(debug == true) { $('#error').append('<div>setSubSections</div>'); }

	if($('#content .section').length > 1) { // if there is more than 1 section on a page
	
		setSecondaryNav();
		showHideScrollers('show');
		
		vScroll = 'scroll';
		
	} else {
		showHideScrollers('hide');
	}

}



function showHideScrollers(vState) { if(debug == true) { $('#error').append('<div>showHideScrollers</div>'); }
	
	if(vState == 'show') {
		$('#up').append('<a href="" class="ir png_bg">Previous Section</a>');
		$('#down').append('<a href="" class="ir png_bg">Next Section</a>');
		
		setScrollerLinks('scroll'); // set the position of bottom scroll
		
	} else if(vState == 'hide') {
		$('.scroller a').hide();
	}
	
	setScrollerPos(); // set the position of bottom scroll

}


function setScrollerPos(vTest) { if(debug == true) { $('#error').append('<div>setScrollerPos</div>'); }
	
	$('.section .bg_img').hide();
	vHeight = $(window).height() - vHeaderHeight - vScrollerHeight - vAvailableHeight; // find the viewable height of the browser window and remove the height above
	//CSS = "'padding-bottom',"+vHeight; // neeed for IE
	
	$('#ajaxContent').css('padding-bottom',vHeight); // set the padding of the content at the bottom
	
	vHeight = vHeight + 4; // add an offset of 4 to accomodate for transparency of scrollers (NEED TO CLARIFY THIS)
	if(vHeight < vScrollerHeight) { // Set the height of the bottom scroller
		$('#down').height(vScrollerHeight);
		//$('#main #down a').height(vScrollerHeight);
	} else {
		$('#down').height(vHeight);
		//$('#main #down a').height(vHeight);
	}
	$('.section .bg_img').show();
	
}

var scrollerPrev = '';
var scrollerNext = '';

function setSecondaryNavCurrent(vEvent) { if(debug == true) { $('#error').append('<div>setSecondaryNavCurrent</div>'); }

	var scrollPos = Math.floor(($(window).scrollTop()+(vAvailableHeight/2))/vAvailableHeight); // Find the scroll position and reduce it to a small number representing the section
	
	$('ul#secondary li').each(function(index) { // cycle through the secondary nav and add/remove the class to the relevant links
		if(index == scrollPos) {
			$(this).addClass('current');
			
			scrollerPrev = $(this).prev().find('a').attr('href');
			scrollerNext = $(this).next().find('a').attr('href');
			
			if(vEvent == 'scroll') {
				vHash = $(this).find('a').attr('href');
				//alert(vHash);
				vlength = vHash.length; //get length of the url string
				//alert(length);
				vpos = vHash.indexOf("#", 0); //get position of the 1st instance of /
				//alert(pos);
				vHash = vHash.substring(vpos,vlength); //cut a new string using 2 values above.
				//alert(vHash); // return the value
				
				window.location.hash = vHash; //change the url hash to the current value
			}
			
		} else {
			$(this).removeClass('current');
		}
	});
	
	$('#promos li').each(function(index) { // cycle through the secondary nav and add/remove the class to the relevant links
		if(index+1 == scrollPos) {
			$(this).addClass('current');
		} else {
			$(this).removeClass('current');
		}
	});
	
	if(vEvent != 'load') {
		setScrollerLinks()
	}
	
}

function setScrollerLinks() { if(debug == true) { $('#error').append('<div>setScrollerLinks</div>'); }
	
	if(typeof(scrollerPrev) === 'undefined') {
		$('#up a').attr('href','javascript:void(0)') // set the link void
	} else {
		$('#up a').attr('href',scrollerPrev) // set the link to the value of the previous setion
	}
	
	if(typeof(scrollerNext) === 'undefined') {
		$('#down a').attr('href','javascript:void(0)') // set the link void
	} else {
		$('#down a').attr('href',scrollerNext) // set the link to the value of the next setion
	}
	
}
	
	
	
function setSecondaryNav() { if(debug == true) { $('#error').append('<div>setSecondaryNav</div>');}
	
	$('nav ul li.current ul#secondary').fadeIn();
	
	//position secondary navigation
	var navPos = vHeaderHeight + vScrollerHeight + ((vAvailableHeight/2) - ($('#nav ul#secondary').height()/2));
	
	// if ie6 change navpos value
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
	 
		var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
	 
		if (ieversion==6) {
			navPos = (vAvailableHeight/2) - $('#nav ul#secondary').height();
		}
	}	
	
	//alert('vHeaderHeight = '+vHeaderHeight+'\n\n'+'vScrollerHeight = '+vScrollerHeight+'\n\n'+'vViewableHeight = '+vViewableHeight+'\n\n'+'navHeight = '+$('nav ul#secondary').height()/2+'\n\n'+'navPos = '+navPos)
	//alert(navPos);
	$('#nav ul#secondary').css('top',navPos);
	$('#nav ul#secondary').show();
	
	setSecondaryNavCurrent('load');
		
}


	
function setPromos() { if(debug == true) { $('#error').append('<div>setPromos</div>'); }

    $('#promos .subPages').each(function() {
        myHTML = $(this).html();
        $(this).prev().append('<ul>'+myHTML+'</ul>')
        $(this).remove();
    });
    	
	$('#promos').each(function(index) {
		if($(this).height() <= 250) {
			$(this).height(250); 
		} else if($(this).height() <= 375) {
			$(this).height(375); 
		} else if($(this).height() <= 500) {
			$(this).height(500); 
		}
	});

	/*if(vViewableIndex*125 > $('.section').height()) { // if handheld
		vViewableIndex = 6;
	}
	
	var myhtml = '<ul class="col2">';
	
	$('#promos li').each(function(index) { 
		
		if(index+1 > vViewableIndex){
			myText = $(this).html();
		 	myhtml += '<li>'+myText+'</li>';
		 	$(this).remove();
		}
	});
	
	myhtml += '</ul>';
	
	$('#promos').append(myhtml);
	
	
	fadePromos();*/

}


/*function fadePromos() { if(debug == true) { $('#error').append('<div>fadePromos</div>'); }

	$("#promos li").each(function(index) {
	    $(this).delay(400*index).fadeIn(300, function(){
	    	if($('#promos').attr('class') != 'notfixed') {
		    	$(this).find('span').fadeIn(200);
		    	textHeight = $(this).find('span').height();
		    	textPadding = (125 - textHeight)/2;
		    	$(this).find('a').css('padding-top',textPadding);
		    	$(this).find('a').css('padding-bottom',textPadding);
		    	$(this).find('a').height(textHeight);	
		    }
	    });
	});

}*/

// set the position of the content
function setContentPos() { if(debug == true) { $('#error').append('<div>setContentPos</div>'); }
	getHeight();
	//$('.section .companies').each(function(index) { // cycle through the sections and position the content vertically centered
	//	var contentPos = ((vViewableHeight - $(this).height())/2);
	//	$(this).css('padding-top',contentPos);
	//});	
	
	//alert(vViewableHeight)
	if(window.location.href.indexOf('news') == -1){
		$('.section').height(vAvailableHeight);
	}else{
		if($('.section > div').first().height() > vAvailableHeight)
			$('.section').height($('.section > div').first().height());
		else
			$('.section').height(vAvailableHeight);
	}	
	
	//$('.bg_img').height(vViewableHeight);
	
	vPadding = 96;
	
	if(!navigator.userAgent.match(/iPad/i)){
		$('#main .section div.inner').each(function(index) {
			if($(this).height()+vPadding <= 250) {
				$(this).height(250-vPadding); 
			} else if($(this).height()+vPadding <= 375) {
				$(this).height(375-vPadding); 
			} else if($(this).height()+vPadding <= 500) {
				$(this).height(500-vPadding); 
			}
			//alert($(this).find('.innerContent').height()+' and '+vViewableHeight )
			//alert($(this).parents('.section').height() + ' and '+ $(this).height())
	
			//if($(this).find('.innerContent').height() + vPadding > vAvailableHeight) {
			//alert('true')
			//	$(this).find('.innerContent').height($(this).parents('.section').height() - vPadding); 
				//alert($(this).find('.innerContent').height();
			//}
			
		});
	}
	
	
	
}


imgWidth = 1600;
imgHeight = 720;

function setBGImg() { if(debug == true) { $('#error').append('<div>setBGImg</div>'); }

screenWidth = $(window).width();
screenHeight = vAvailableHeight;
//alert('screenWidth='+screenWidth+' and '+'screenHeight='+screenHeight);
	
	if(!fullOverride || $('.subCompany').length != 0) {
		if(bgImgShow || staticOverride || $('.subCompany').length != 0) {
			
			$('.bg_img img').show()
				
			if(($('.subCompany').length != 0 && !staticOverride && !bgImgShow) || fullOverride) {
				$('.bg_img img').hide()
				$('.bg_img.subCompany img').show()
			}
				
			$('.section .bg_img img').each(function(index) {
				bgWidth = $(this).width();
				bgHeight = $(this).height();
				
				widthDiff = screenWidth - imgWidth;
				heightDiff = screenHeight - imgHeight;
				//alert('widthDiff='+widthDiff+' and '+'heightDiff='+heightDiff);
				
				//alert(widthDiff+' '+heightDiff)
				if(widthDiff > heightDiff) {
					if(screenWidth < imgWidth) {
						//alert('1');
						$(this).width(imgWidth);
						$(this).height(imgHeight);
					} else {
						//alert('2');
						$(this).width(screenWidth);
						
						bgRatio = screenWidth/imgWidth;
						bgNewHeight = imgHeight * bgRatio;
						$(this).height(bgNewHeight);
					}
				} else {
					if(imgHeight < vAvailableHeight) {
						//alert('3');
						$(this).height(vAvailableHeight);
						bgRatio = vAvailableHeight/imgHeight;
						bgNewWidth = imgWidth * bgRatio;
						$(this).width(bgNewWidth);
					} else {
						//alert('4');
						$(this).width(imgWidth);
						$(this).height(imgHeight);
					}
				}
				
				$(this).parents('.bg_img').width(screenWidth);
				$(this).parents('.bg_img').height(vAvailableHeight);
				
			});
	
		}
	}
}

function setiPadBG(){
	if($(window).height() > $(window).width()){
		//it's portrait
		$('.bg_img').find('img').attr('height',$(window).height() - vHeaderHeight - (vScrollerHeight)*2);
		
	}else{
		//it's landscape
		$('.bg_img').find('img').removeAttr('height');
	}
	
		
}

function scrollScreen(element) { if(debug == true) { $('#error').append('<div>scrollScreen</div>'); }
	
	var targetHref = '';
	
	if(element == 'load') { // if this occurs when the page loads (as opposed to when we are clicking secondary nav)
        //alert('here')
		targetHref = window.location.hash; // get hash value of the url
		if(targetHref == "" ) { //test whether there is a hash value
			targetID = '#'+$('#main .section').attr('id');
		} else {
			cutID(targetHref)
		}
		
	} else {
		targetHref = $(element).attr("href");
		//alert('targetHref= '+targetHref)
		cutID(targetHref);
	}
	
	//alert((targetHref.split("/").length - 1)) //3)
	if(targetHref.split("/").length > 1) {
		//alert('targetID= '+targetID);
		// The location of the target div layer in relation to the browser window
		
		var targetPostion = $(targetID).offset().top - vHeaderHeight - vScrollerHeight; // Header/scroller offset
		// The speed of the animation in millisenconds
		var speed = 500;
		
		var selector = "html:not(:animated),body:not(:animated)"; 
		// We then use the animation function to scroll the main window
		$(selector).animate({ scrollTop: targetPostion }, speed);
		
	} else {
		return false;
	}
               
}

})(this.jQuery);

//NOTE: MS removed this funciton from the above jQuery wrapper as it needs to be defined before

function cutID(targetHref) {
	//alert('targetHref ='+targetHref)
	var vlength = targetHref.length; //get length of the url string
	//alert('length ='+vlength)
	var vpos = targetHref.indexOf("#", 0) + 2; //get position of the 1st instance of /
	//alert('pos ='+vpos)
	targetID = targetHref.substring(vpos,vlength) //cut a new string using 2 values above.
	//alert(targetID)
	
	vpos = targetID.indexOf("/", 0)+1; //get position of the 2nd instance of /
	targetID = '#'+targetID.substring(vpos,vlength) //cut a new string using 2 values above.
	
	return targetID; // return the value
}




// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};



// catch all document.write() calls
(function(doc){
  var write = doc.write;
  doc.write = function(q){ 
    log('document.write(): ',arguments); 
    if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);  
  };
})(document);



