//
var currentLinearPage = 0;
var currentPage = 0;
var movementDistance = 0;
var movementHeightDistance = 0;
var showview = "home";
var nextText = "";
var prevText = "";
var curHash = "";
var ie7 = (typeof document.addEventListener != 'function' && window.XMLHttpRequest) ? true : false;
var hashToPage = [ {hash: '#home', page: 0},{hash: '#howwehelp', page: 1}, {hash: '#whoweare', page: 2}, {hash: '#successstories', page: 3}, {hash: '#rightforyou', page: 4}, {hash: '#billrate', page: 5}, {hash: '#projecteconomy', page: 6} ];

//
$(function(){
		
	adjustHeight();
	
	$('#view-control li.home, .linear-view, .grid-view').click(function(){
		if($(this).hasClass('active')){
			return false;
		} else {
			$('#view-control li.active').removeClass('active');
			activateView($(this).attr('class').split(' ')[0]);
			$(this).addClass('active');
		}
	});

	
	//
	$( '#hiddenGrid' ).hide();
	$('.grid').hide();
	
	//do not show prev
	$( '#page-up, #page-down' ).addClass('disabled');
	
	//
	$('#linear-view li').each(function(e){
		$(this).addClass('linear-'+e);
	});
	
	$('#linear-view li.linear-0').addClass('current-view');
	
	//
	updateLeftNav(0);
	//updatePageNav();
	//
	$('ul.section li a').click(function(){
		// show linear view of widget
		// update nav items
		if(showview=="grid-view" || showview =="home"){
			showview = "linear-view";
			$( '#page-down' ).removeClass('disabled');
			//if(currentLinearPage != 0 || currentLinearPage != 1) $('#page-up').removeClass('disabled');
			$( '#top-sensor, #bottom-sensor' ).show();
			$('.grid, .pager').hide();
			$('#linear-view').show();
			$('#view-control li.active').removeClass('active');
			$('#view-control li.linear-view').addClass('active');
			adjustHeight();
		}
		var parentClass = $(this).parent('li').attr('class');
		var lastChar = parentClass.charAt(parentClass.length-1);
		updateLeftNav(lastChar);
	});
	
	//
	$('#top-sensor, #bottom-sensor').hover(function(){
		showArrow($(this).find('div'), true);
	}, function(){
		showArrow($(this).find('div'), false);
	});
	
	
	// Content Container
	$(window).resize(adjustHeight);
	
	//was a hash nav value passed
	if( location.hash != "" && location.hash != null )
	{
		//
		curHash = location.hash;
	
		//navigate to that item with animation
		doMoveToLinearWithHash( location.hash );
		if(location.hash != "#home"){
			$('#view-control li.active').removeClass('active');
			$('#view-control li.linear-view').addClass('active');
		}
		if(location.hash == "#billrate"){
			$('#top-sensor, #bottom-sensor').addClass('light');
			Cufon.refresh();
		} else {
			$('#top-sensor, #bottom-sensor').removeClass('light');
			Cufon.refresh();
		}
		/*if(location.hash == '#billrate') {
		$('head').append('<link type="text/css" media="screen" rel="stylesheet" href="/sites/mbopartners.com/themes/mbopartners/css/widgets/billrate/billrate.css" />');
		} else {
			$('head').remove('<link type="text/css" media="screen" rel="stylesheet" href="/sites/mbopartners.com/themes/mbopartners/css/widgets/billrate/billrate.css" />');
		}*/
		
	}
	
	// onload add #home hash
	if(window.location.hash == ''){
		doMoveToLinearWithHash('#home');
		location.hash = '#home';
	}
	
	//maybe better detection here?
	if( ie7 )
	{
		//
		setInterval(function()
		{
			//
	 		if (curHash != window.location.hash)
	 		{
	 			//
	  			curHash = window.location.hash;
  			
  				//
  				detectHash();
			}
		}, 10);
	}
	
	//should determine if the window object has changed....
	$(window).bind('hashchange', detectHash );
		
	//
	//a.primary-link, #tertiary-nav ul li,  .ave, #subheader h3, #columns h3, #left-nav li, #search-content-area #col2 h2, #callout h3.title, .front .featured-event h3
});

function detectHash()
{
		closeOverlay();
		//was a hash nav value passed
		if( location.hash != "" && location.hash != null )
		{
			//navigate to that item with animation
			doMoveToLinearWithHash( location.hash );
			if(location.hash == "#home"){
				$('#view-control li.active').removeClass('active');
				$('#view-control li.home').addClass('active');
			}
			if(location.hash != "#home"){
				$('#view-control li.active').removeClass('active');
				$('#view-control li.linear-view').addClass('active');
			}
		}
		if(location.hash == "#billrate"){
			$('#top-sensor, #bottom-sensor').addClass('light');
			Cufon.refresh();
		} else {
			$('#top-sensor, #bottom-sensor').removeClass('light');
			Cufon.refresh();
		}
		if(location.hash == ''){
			doMoveToLinearWithHash('#home');
			location.hash = '#home';
		}
		/*if(location.hash == '#billrate') {
		$('head').append('<link type="text/css" media="screen" rel="stylesheet" href="/sites/mbopartners.com/themes/mbopartners/css/widgets/billrate/billrate.css" />');
		} else {
			$('head').remove('<link type="text/css" media="screen" rel="stylesheet" href="/sites/mbopartners.com/themes/mbopartners/css/widgets/billrate/billrate.css" />');
		}*/
}

function arrowColor(active){
	$('#top-sensor, #bottom-sensor').addClass('light');
	$('#top-sensor, #bottom-sensor').removeClass('light');
	Cufon.refresh();
}

function showArrow(arrow, state){
	if(arrow.hasClass('disabled')){
		arrow.hide();
		return;
	}
	if(state==true) arrow.show();
	if(state == false) arrow.hide();
}

function activateView(view){
	if(view == "home"){
		showview = "home";
		$( '#top-sensor, #bottom-sensor' ).hide();
		$('.grid, .pager').hide();
		$('#linear-view').show();
		updateLeftNav(0);
		doMoveToLinear(0);
	}
	if(view == "linear-view"){
		showview = "linear-view";
		$( '#top-sensor, #bottom-sensor' ).show();
		$('.grid, .pager').hide();
		$('#linear-view').show();
		if(currentLinearPage == 0) { 
			currentLinearPage = 1;
		}
		location.hash = hashToPage[ currentLinearPage ].hash; 
		updateLeftNav(currentLinearPage);
		doMoveToLinear(currentLinearPage);
		updatePageNav();
	}
	if(view == "grid-view"){
		showview = "grid-view";
		appendItems();
		//doMoveToLinear(1);
		updateLeftNav(-1);
		$('#linear-view').hide();
		$('#top-sensor, #bottom-sensor').hide();
		$('.grid, .pager').show();
	}
	adjustHeight();
	Cufon.refresh();
}

//
function updateLeftNav(navItem){
	$('#widget-nav li.active-widget').removeClass('active-widget');
	$('#widget-nav li.linear-'+navItem).addClass('active-widget');
	
	//
	Cufon.refresh();
}

//
function updatePageNav(){
	nextText = $('li.linear-'+(currentLinearPage+1)+' a').attr('title');
	prevText = $('li.linear-'+(currentLinearPage-1)+' a').attr('title');
	$('#page-down p').html(nextText);
	$('#page-up p').html(prevText);
	
	//
	Cufon.refresh();
}

function appendItems(){
	//
	$('#grid-twitter').append($('#home-tweet'));
	$('#grid-blog-post').append($('#home-blog-post'));
	$('#grid-research').append($('#resource-wrapper'));
	$('#grid-event').append($('#home-event'));
	$('#grid-press-release').append($('#home-press-release'));
}

	//
function doPrev()
{
	//console.log( 'do prev:' );
	//console.log(currentPage);

		//
	if( currentPage == 0 )
		return;
	
		//toggle on prev and next buttons
	$( '#btn-prev' ).show().removeClass('disabled');
	$( '#btn-next' ).show().removeClass('disabled');
	$('.pager .current-page').removeClass('current-page');

		
		//
	$( '.grid' ).each( function()
	{
			//
		$( this ).animate({ left: '+=' + movementDistance }, { duration: 200 } );
	});

		//
	currentPage--;
	
	$('.pager .page-'+currentPage).addClass('current-page');
	
	$('.grid.current-page').removeClass('current-page');
	$('.page'+currentPage).addClass('current-page');
	
	//
	if( currentPage == 0)
		$( '#btn-prev' ).addClass('disabled');
	
}

//
function doMoveTo( pageNum )
{
	//console.log( 'move to:' );
	//console.log(pageNum);
	//console.log(currentPage);

		//
	if( pageNum == currentPage )
		return;
		
		//toggle on prev and next buttons
	$( '#btn-prev' ).show().removeClass('disabled');
	$( '#btn-next' ).show().removeClass('disabled');
	$('.pager .current-page').removeClass('current-page');
	
		//if this is the first page hide prev	
	if( pageNum == 0)
		$( '#btn-prev' ).addClass('disabled');
		
		//if this is the last page hide next
	if( (pageNum + 1) == $( '.grid' ).length  )
		$( '#btn-next' ).addClass('disabled');
		
		//
	var moveAmount = (movementDistance * (currentPage - pageNum) );
	
		//
	$( '.grid' ).each( function()
	{
			//
		$( this ).animate({ left: '+=' + moveAmount }, { duration: 200 } );
	});
	
		//
	currentPage = pageNum;
	
	$('.grid.current-page').removeClass('current-page');
	$('.page'+currentPage).addClass('current-page');
	
	$('.pager .page-'+currentPage).addClass('current-page');

}

//
function doNext()
{
	//console.log( 'do next:' );
	//console.log("current page: " + currentPage);
	//console.log("length of grids: " + $( '.grid' ).length);

	
		//
	if( (currentPage + 1) == $( '.grid' ).length )
		return;
	
	//toggle on prev and next buttons
	$( '#btn-prev' ).show().removeClass('disabled');
	$( '#btn-next' ).show().removeClass('disabled');
	$('.pager .current-page').removeClass('current-page');
	
		
		//
	$( '.grid' ).each( function()
	{
			//
		$( this ).animate({ left: '-=' + movementDistance }, { duration: 200 } );
	});

		//
	currentPage++;
	$('.pager .page-'+currentPage).addClass('current-page');
	
	$('.grid.current-page').removeClass('current-page');
	$('.page'+currentPage).addClass('current-page');
	
	//
	if( currentPage == ($( '.grid' ).length-1) )
		$( '#btn-next' ).addClass('disabled');
}

//
function doPrevLinear()
{
		//
	if( currentLinearPage == 1 )
		return;
	
		//toggle on prev and next buttons
	$( '#page-up' ).removeClass('disabled');
	$( '#page-down' ).removeClass('disabled');
		
		//
	$( '.linear-item' ).each( function()
	{
			//
		$( this ).animate({ top: '+=' + movementHeightDistance }, { duration: 200 } );
	});

	$('#linear-view li.current-view').removeClass('current-view');
		//
	currentLinearPage--;
	
	$('#linear-view li.linear-'+currentLinearPage).addClass('current-view');
	//
	if (currentLinearPage == 1){
		$( '#page-up' ).addClass('disabled');
		$('#page-down').removeClass('disabled');
		showArrow($('#top-sensor div'), false);
	}
	
	//loop through the hash to page array
	for( var i = 0; i < hashToPage.length; i++ )
	{
		//is this the same hash?
		if( hashToPage[ i ].page == currentLinearPage )
		{
			//set the new hash value
			location.hash = hashToPage[ i ].hash;
		
			//stop now
			break;
		}
	}
		
	updateLeftNav(currentLinearPage);
	updatePageNav();
}

//
function doNextLinear()
{
		//
	if( (currentLinearPage+ 1) == $( '.linear-item' ).length )
		return;
	
		//toggle on prev and next buttons
	$( '#page-up' ).removeClass('disabled');
	$( '#page-down' ).removeClass('disabled');
		
		//
	$( '.linear-item' ).each( function()
	{
			//
		$( this ).animate({ top: '-=' + movementHeightDistance }, { duration: 200 } );
	});
	
	$('#linear-view li.current-view').removeClass('current-view');
		//
	currentLinearPage++;
	
	$('#linear-view li.linear-'+currentLinearPage).addClass('current-view');
	
	//
	if( currentLinearPage == ( $( '.linear-item' ).length - 1 ) ){
		$( '#page-down' ).addClass('disabled');
		showArrow($('#bottom-sensor div'), false);
	}
	
	//loop through the hash to page array
	for( var i = 0; i < hashToPage.length; i++ )
	{
		//is this the same hash?
		if( hashToPage[ i ].page == currentLinearPage )
		{
			//set the new hash value
			location.hash = hashToPage[ i ].hash;
		
			//stop now
			break;
		}
	}
	
	updateLeftNav(currentLinearPage);
	updatePageNav();
}


//
function doMoveToLinear( pageNum )
{	
	
	if( pageNum == 0 || pageNum == 1) {
		$( '#page-up' ).addClass('disabled');
	} else {
		$( '#page-up' ).removeClass('disabled');
	}
	if(pageNum == 0){
		$('#page-down').addClass('disabled');
	}
	if(pageNum != 0){
		$('#page-down').removeClass('disabled');
	}
	if(pageNum == ($('.linear-item').length-1))
		$('#page-down').addClass('disabled');
		
	if( pageNum == currentLinearPage )
		return;
	
		//
	var moveAmount = (movementHeightDistance * (currentLinearPage - pageNum) );
	
		//
	$( '.linear-item' ).each( function()
	{
			//
		$( this ).animate({ top: '+=' + moveAmount }, { duration: 200 } );
	});
	
		//
	currentLinearPage = pageNum;
	
	if(pageNum == ($('.linear-item').length-1))
		$('#page-down').addClass('disabled');
	
	$('#linear-view li.current-view').removeClass('current-view');
	$('#linear-view li.linear-'+currentLinearPage).addClass('current-view');
	
	//loop through the hash to page array
	for( var i = 0; i < hashToPage.length; i++ )
	{
		//is this the same hash?
		if( hashToPage[ i ].page == currentLinearPage )
		{
			//set the new hash value
			location.hash = hashToPage[ i ].hash;
		
			//stop now
			break;
		}
	}
	
	updateLeftNav(currentLinearPage);
	updatePageNav();
}

//
function doMoveToLinearWithHash( hash )
{
	//loop through the hash to page array
	for( var i = 0; i < hashToPage.length; i++ )
	{
		//is this the same hash?
		if( hashToPage[ i ].hash == hash )
		{
			//
			doMoveToLinear( hashToPage[ i ].page );
		
			//stop now
			break;
		}
	}
}

//displays an overlay of the widget to the user
function displayOverlay( nid, css, js )
{
	//no content? no reason to do a thing
	if( nid == null || nid == "" )
		return;

	//
	$.modal('<div id="overlay"></div>',{onClose: function(){ removeFilter(); $.modal.close(); }, ContainerCss:{width:"auto",height:"auto"}, onShow: function(dialog){
		$('#simplemodal-container').css({"top":"0px"});
		$('#overlay').append('<div class="widget-loader"><p>Loading...</p></div>');

		adjustHeight();
		
		//load the content from the provided URL
		$("#overlay").load( "http://www.mbopartners.com/node/" + nid, function(response, status, xhr)
		{
				//
			if (status == "error")
			{
				//
				//var msg = "Sorry but there was an error: ";
				//$("#error").html(msg + xhr.status + " " + xhr.statusText);
			}
			
				//
			else
			{
				//
				$('.widget-loader').remove();
				
				//
				$("#overlay").html( xhr.responseText );
				
				$('#overlay').css({height:Math.floor($(window).height()-25)});
				
				if($('#overlay object').length){
					$('#overlay object').css({'visibility': 'visible'});
				}
			}
		});
	}});
	
	
}

function removeFilter(){
	$('.view-WidgetLinear').css({'filter':'none'});
}

	//
function adjustHeight()
{	
	// content background width/height
	var docWidth = Math.floor($(window).width() - 260);
	var docHeight = Math.floor($(window).height() - 100);
	
	//sets the distance that all animations will occur over
	movementDistance = docWidth;
	


	if(showview == "grid-view"){ 
		//always move back to screen one when we do a resize action
		doMoveTo( 0 );
		
		$('#content-inner').css({width:docWidth});
		$('#content-area').css({width:docWidth});
	
		$('#content-inner').css({height:docHeight});
		$('#content-area').css({height:docHeight});
	}
	
	
	
	if($('#overlay').length){
		$('#overlay').css({height:docHeight+72});
	}
	
	if(showview == "linear-view" || showview == "home")
	{
		
		//
		if(docWidth <= 724){
			$('#content-inner, #content-area, .linear-item').css({width:724});
		} else {
			$('#content-inner, #content-area, .linear-item').css({width:docWidth});
		}
	
		if(docHeight <= 624){
			 $('#content-inner, #content-area, .linear-item').css({height:624});
			 docHeight = 624;
			 movementHeightDistance = docHeight;
		} else {
			$('#content-inner, #content-area, .linear-item').css({height:docHeight});
			docHeight = Math.floor($(window).height() - 100);
			movementHeightDistance = docHeight;
		}
		
		if(showview == "home"){
			var width  = $('#linear-view .super-image').width();
			var height = $('#linear-view .super-image').height();
			var parentWidth  = $('#linear-view .super-image').parent().width();
			var parentHeight = $('#linear-view .super-image').parent().height();
		
			if(width/parentWidth < height/parentHeight)
			{
					newWidth  = parentWidth;
					newHeight = newWidth/width*height;
			}
			else
			{
					newHeight = parentHeight;
					newWidth  = newHeight/height*width;
			}
			margin_top  = (parentHeight - newHeight) / 2;
			margin_left = (parentWidth  - newWidth ) / 2;
		
			$('#linear-view .super-image').css({/*'margin-top' :margin_top  + 'px',*/
						 'margin-left':margin_left + 'px',
						 'height'     :newHeight   + 'px',
						 'width'      :newWidth    + 'px'});
		}
		
		
		//
		var moveAmount = ( movementHeightDistance * currentLinearPage );

		//
		var nextTop = -moveAmount;
	
		//
		$( '.linear-item' ).each( function()
		{
			//
			//var topPos = $(this).css('top');
			$(this).css( 'top', nextTop );
			
			//
			nextTop += docHeight;
		});
		
		//$('.widget-content').width(docWidth/2).height(docHeight/2).css({'margin-left':-(docWidth/4), 'margin-top':-(docHeight/4)});
		//$('.widget-content').css({'margin-top':-(docHeight/4)});	
		
		//
		return;	
	}
		
	if(showview == "grid-view"){ 
		//
		var minWidth = 250;
		var minHeight = 180; 
		
		//
		var numColumns = Math.floor( (docWidth-15)/minWidth );
		var numRows = Math.floor( (docHeight-130)/minHeight );
		
		//
		var itemWidth = Math.floor((docWidth-19) / numColumns) - ( 9 );
		var itemHeight = Math.floor((docHeight-35) / numRows) - ( 20 );
		
		//initial vars for moving into slots
		var page = 0;
		var currentItem = 0;
		// calculate how many items can fit on a page
		var totalItemsPage = numColumns * numRows;
		// get length of total list
		var totalItems = $( '#hiddenGrid .item' ).length +1;
		// project amount pages on load
		var totalPages = Math.ceil( totalItems/totalItemsPage );
		
		//console.log('totalItemsPage: '+totalItemsPage+ ' totalItems: '+totalItems+' totalPages: '+totalPages);
		
		//remove content from all prior pages
		$( '.page' ).empty();	
		
		//remove all prior pages
		$( '.page' ).remove();
		
		//empty out the grid
		$( '.grid' ).empty();
		
		//add a pager for stepping back and forward
		if( totalPages > 1 )
		{
			//do we need to add a pager or do we have one?
			if( $( '.pager' ).length == 0 )
			{
				//
				$( '#content-area' ).append( '<div class="pager"></pager>' );
				
				//
				$( '.pager' ).css( 'position', 'absolute' );
			}
			
			//
			var pagerContent = '<a href="javascript:;" id="btn-prev" onclick="doPrev()"></a> ';
			
			//
			for( var i = 0; i < totalPages; i++ )
			{
				//
				//console.log( "current page: " + i );
				
				//
				pagerContent += '<a href="javascript:;" class="control page-'+i+'" onclick="doMoveTo(' + i +');"></a>';
			}
	
				
			//
			pagerContent += '<a href="javascript:;" id="btn-next" onclick="doNext()"></a>';
			
			//
			$( '.pager' ).html( pagerContent );
			
			//position the pager properly
			$( '.pager' ).css( 'left',  ( ( docWidth/2 ) - ( $( '.pager' ).width()/2 ) ) + 'px' );
			$( '.pager' ).css( 'bottom', '1px' );
			
			// set active page
			$('.pager a.page-0').addClass('current-page');
			
			//make the button invisible
			$( '#btn-prev' ).addClass('disabled');
		}
		
		if(totalPages == 1){
			$('.pager').remove();
		}
		
		//step through all the grids to use
		$( '#hiddenGrid' ).children().each( function()
		{
			//
			var thisItem = $(this).clone();
				
			//do an extra increment if this is a double wide
			if( $( this ).hasClass( '.two-wide' ) )
				currentItem++;
			
			//
			$( '.page'+page ).append( thisItem );
			
			//increment the current item
			currentItem++;
			
			//
			if( currentItem >= totalItemsPage )
			{		
				//reset the current item we are on
				currentItem = 0;
				
				//increment to the next page to fill
				page++;
				
				//append a new page div
				$( '#content-area' ).append( '<ul class="grid page page' + page + '"></ul>' );
				
					//position this item relative to the others
				$( '.page' + page ).css( 'top', 0 );				
				$( '.page' + page ).css( 'left', docWidth * page );
				
			}
		
			//
			$( '.grid' ).css( 'width', docWidth - 10);
			$( '.grid' ).css( 'height', docHeight - $( '.pager' ).height() - 5);
			
		});
		
		// set grid item width and height
		$('.grid .item').css('width',itemWidth);
		
		//
		$('.grid .two-wide').css('width',itemWidth*2+11);
		
		//
		$('.grid .item').css('height',itemHeight);
		
		//
		$('.grid .item-wrapper').css({'width':itemWidth, 'height':itemHeight+9});
		
		//
		$('.grid .two-wide .item-wrapper').css({'width':itemWidth*2+11});
		
		
		$('.page0').addClass('current-page');
		
		// add last class to remove right borders from last elements in row

		var listLength = $('.current-page li').length;
	
		
		$('.grid li:nth-child('+(numColumns)+'n)').addClass('last');
		

		$('.current-page li').removeClass('last');

		$('.grid li').eq($('.grid li').length-1).addClass('last');
		
		
		// resize image
		/*var iwidth  = $('.grid .super-image').width();
		var iheight = $('.grid .super-image').height();
		var parentWidth  = $('.grid .super-image').parent().width();
		var parentHeight = $('.grid .super-image').parent().height();
		if(iwidth/parentWidth < iheight/parentHeight)
		{
				newWidth  = parentWidth;
				newHeight = newWidth/iwidth*iheight;
		}
		else
		{
				newHeight = parentHeight;
				newWidth  = newHeight/iheight*iwidth;
		}
		margin_top  = (parentHeight - newHeight) / 2;
		margin_left = (parentWidth  - newWidth ) / 2;
	
		$('.grid .super-image').css({
					 'margin-left':margin_left + 'px',
					 'height'     :newHeight   + 'px',
					 'width'      :newWidth    + 'px'});
					 */
		
		firstIn = true;
		
		for(i=listLength-1;i>=0;i-=numColumns){
			$('.current-page li').eq(i).addClass('last');
			if(firstIn == true){
				i+= Math.abs(listLength-totalItemsPage)-1;
				firstIn = false;
			}
		}
		//
		$('.item').hover(function(){
			$(this).find('.rollover .roll-content').css({'width':itemWidth-40, 'height':itemHeight, 'margin-top':-(itemHeight/2)/2, 'margin-left':-(itemWidth-40)/2});
			$(this).find('.rollover').show();
		}, function(){
			$(this).find('.rollover').hide();
		});
	}
	Cufon.refresh();

}
