var scrollPane;
var scrollContent;
var scrollbar;
var handleHelper;
var numArticleRows;
var articleHeight = 162;
var selectedArticleIndex = -1;
var curWorkType = 'all';
var curClientType = 'all';
var curArticleID;
//var curSortType = 'newest';

var articleIsLoaded = false;
var refreshOnURLChange = true;

/********RA - 06/08/11	******/
var initialLoadedProjects = 50;
var projectsOnNewPage = 50;
var featuredOnPage = 25;
/****************************/
var featuredLoaded = "";

var slideshowCurIndex = 0;
var loadingArticles = false;
var loadedArticles = 0;
var searchMetaColumnWidth = 150;

var touchScroller;
var scrollThumbDown = false;

$(document).ready(function() {
	
	
	//isTouch = true;
	
	if (isTouch) {
        addSwipe();
        $('#scrollTrack').css('top','53px');
    } else {
    	
        initScrollBar();
    }
        
});

//change handle position on window resize
$(window).resize(function(){
	if(selectedArticleIndex == -1) reflowColumns();
	if (!isTouch) {
		resetValue();
		sizeScrollbar();
	}else{
		//window.location.reload();
	}
	reflowContent();
});

//if user releases the scroll thumb outside of the window, load more articles
$(document).mouseleave(function(){
	if(scrollThumbDown)
		loadMoreArticles();
});

function adjustNavLayout() {

	
	var navWidth = 290 + $('#nav').width() + $('#secondNav').width();
	$('#navHolder').css('min-width',navWidth+'px');
	

}

function addSwipe() { 

	scrollContent = $('.scroll-content');
	scrollPane = $('#swipeScrollPane');
	
	
	var scrollNode = document.getElementById("swipeScrollPane"), options = {elastic: true};
	
	touchScroller = new TouchScroll(scrollNode, options);
	
	
	document.getElementById('swipeScrollPane').addEventListener("touchend", onTouchEnd, false);
}

function onTouchEnd() {

	
	//alert('mouse down');
	var timeout = window.setTimeout(function(){
		var scrollVal = touchScroller._currentOffset.e * -1;
		//console.log("scroll val: "+scrollVal+", content width: "+$('.scroll-content').width());
		//console.log( touchScroller._getFlickingDuration );
		
		if (scrollVal >=  scrollContent.width() - scrollPane.width() - 80 )
			loadMoreArticles();
	
	}, 2000);
	
	
}

function loadMoreArticles() {

	var pastThreshold = false;
	if (isTouch)
		pastThreshold = true;
	else if ( !isTouch && scrollbar.slider("value") > 85 )
		pastThreshold = true;
		
	if (!loadingArticles && pastThreshold && selectedArticleIndex == -1 ) {
	
		if ( currentSection == "work" || currentSection == "selectedWork" )
			loadArticles('fetchProjects',loadedArticles,projectsOnNewPage,curWorkType,curClientType, curSortType);
		else if ( currentSection == "search" )
			loadArticles('fetchProjects',loadedArticles,projectsOnNewPage,curWorkType,curClientType, curSortType, '', curSearchString );
	}
	
}

function initScrollBar() {
	
	
	//scrollpane parts
	scrollPane = $('.scroll-pane');
	scrollContent = $('.scroll-content');
	
	//build slider
	scrollbar = $(".scroll-bar").slider({
		step:0.1,
		animate: true,
		slide:function(e, ui){
			onScrollChange(ui.value);
		},
		change:function(e, ui){
			onScrollChange(ui.value);
		}
	});
	
	
	//append icon to handle
	handleHelper = scrollbar.find('.ui-slider-handle')
	.mousedown(function(){
		scrollbar.width( handleHelper.width() );
		var offsetfix = (($(".ui-slider-handle").width()/2)*-1)+3;
		scrollThumbDown = true;
	})
	.mouseup(function(){
		scrollbar.width( '100%' );
		loadMoreArticles();
		scrollThumbDown = false;
	})
	.append('<span class="ui-icon ui-icon-grip-dotted-vertical"></span>')
	.wrap('<div class="ui-handle-helper-parent"></div>').parent();
	
	//change overflow to hidden now that slider handles the scrolling
	//scrollPane.css('overflow','hidden');
	
	if( (scrollContent.width() - scrollPane.width()) < 0 ) {
		$(".scroll-bar").slider({ disabled: true });
	}

	
	//init scrollbar size
	setTimeout(sizeScrollbar,10);//safari wants a timeout
}
function onScrollChange(val) {
	var col;
	var leftBoundRatio;
	var rightBoundRatio;
	
	if( scrollContent.width() > scrollPane.width() ){ 
		scrollContent.css('margin-left', Math.round( val / 100 * ( scrollPane.width() - scrollContent.width() )) + 'px');
		//make pagination controls fixed position if project is in viewport
		
		if(articleIsLoaded){
			
			col = Math.ceil((selectedArticleIndex+1)/numArticleRows);
			leftBoundRatio = 100*(((($('.project').width()+45)*col)+45)/scrollContent.width());			
			rightBoundRatio = 100*( ( (projColWidth*col)+$('#articleDetail').width()+760 ) / scrollContent.width() );
			
			var smallArticle = ( $('#articleDetail').width() < $(window).width() ) ? true : false;
			
			if( val < leftBoundRatio && $('#pageHeader').hasClass('fixed') )
				$('#pageHeader').removeClass('fixed');
			else if ( val >= leftBoundRatio && val <= rightBoundRatio && !$('#pageHeader').hasClass('fixed') && !smallArticle )
				$('#pageHeader').addClass('fixed');
			else if ( val > rightBoundRatio && $('#pageHeader').hasClass('fixed') )
				$('#pageHeader').removeClass('fixed');
			
			//console.log( 'current:' +val );
			//console.log( 'left:' +leftBoundRatio );
		}
		
		//load projects at scroll end if not viewing a project and not already loading a project
		
		if( val == 100 ) {
			loadMoreArticles();
		}

		
		
	} else { 
		scrollContent.css('margin-left', 0); 
	}
}

function updateImage(mode){
	
	//alert( $('.articleImage:eq('+slideshowCurIndex+')').attr('width') );
	var shift = $('.articleImage:eq('+slideshowCurIndex+')').attr('width') + 40;
	var curPosStr = $('.scroll-content').css('margin-left');
	var curPosNum = parseFloat( curPosStr.slice(0,curPosStr.length-2) );
	
	if(slideshowCurIndex == 0) //if first next click, add meta width to the shift
		shift += ($(".projectMeta").width()+5);
		
	if(mode != "next" && slideshowCurIndex == 1 ) //if click prev on second image, show meta
		shift += $(".projectMeta").width();
		
	//alert($('.articleImage:eq('+slideshowCurIndex+')').attr('width'));
	
	var newPos = (mode == "next") ?  curPosNum - shift : curPosNum + shift;
	
	//prevent next button from sending content past allowable area
	/*
console.log(curPosNum+', '+$('.scroll-content').width());
	
	if( newPos*-1 > $('.scroll-content').width() )
		newPos = $('.scroll-content').width() * -1;
*/
	
	$('.scroll-content').animate({ 'margin-left' :  newPos }, 
		500, 
		function() {
			updateScroll();
		});	
		
	if(mode == "next")
		slideshowCurIndex++;
	else
		slideshowCurIndex--;
		
	$('#currentImage').html( slideshowCurIndex + 1 );

}

function reflowColumns() {

	var windowHeight = document.documentElement.clientHeight; //$(window).height();
	//var articleHeight = 185;
	var firstTime;
	if(numArticleRows == undefined)
		firstTime = true;
	else
		var oldValue = numArticleRows;
	
	if ( currentSection == "offices" ) 
		numArticleRows = 1;
	else {
	
		if ( windowHeight < (268 + articleHeight) ) {
			numArticleRows = 1;
			
		
		} else if ( windowHeight < (288 + articleHeight*2) ) {
			numArticleRows = 2;
			
			
		} else if ( windowHeight < (336 + articleHeight*3) ) {
			numArticleRows = 3;
			
		} else if ( windowHeight < (336 + articleHeight*4) ) {
			numArticleRows = 4;
			
		} else if ( windowHeight < (336 + articleHeight*5) ) {
			numArticleRows = 5;
			
		} else if ( windowHeight < (336 + articleHeight*6) ) {
			initialLoadedProjects = 128;
			numArticleRows = 6;
			
		} else {
			initialLoadedProjects = 128;
			numArticleRows = 7;
			
		}
		//toggle element visibility to optimize for very short viewports
		if ( windowHeight < (316 + articleHeight*2) ) {
			$('#footer').hide(0);
			$('#swipeScrollPane').css('height',(windowHeight-96)+'px');
		} else {
			$('#footer').show(0);
			$('#swipeScrollPane').css('height','auto');
		}
		if ( windowHeight < (268 + articleHeight) )
			$('#heightWarning').fadeIn(300);
		else
			$('#heightWarning').fadeOut(300);
	
	}
	
	//force new size of scroll content so scroll bar resizes
	if(oldValue != numArticleRows && firstTime != true )	
		$('.scroll-content').width( Math.ceil(loadedArticles/numArticleRows) * projColWidth ); 	
			
	$('#projectsGridHolder').layout({  type: 'grid', rows: numArticleRows } );	
	
	//alert(numArticleRows);
	
}

//size scrollbar and handle proportionally to scroll distance
function sizeScrollbar(){

	var remainder = scrollContent.width() - scrollPane.width();
	var proportion = remainder / scrollContent.width();
	var handleSize;
	if (remainder > 0) {
		handleSize = scrollPane.width() - (proportion * scrollPane.width());
		
		
		scrollbar.find('.ui-slider-handle').css({
			width: handleSize,
			'margin-left': -handleSize/2
		});

		scrollbar.width( '100%' ); //make sure scroll area stays the width of the viewport
		handleHelper.width('').width( scrollbar.width() - handleSize);
		
		$(".scroll-bar").slider({ disabled: false });
		
	} else {
		
		scrollbar.find('.ui-slider-handle').css({
			width: scrollPane.width(),
			'margin-left': 0
		});
		
		handleHelper.width('').width( scrollbar.width() - 0); //0 was handleSize
		
		$(".scroll-bar").slider({ disabled: true });
		
	}
	
	//fix the right arrow padding
	//alert('sized');
	var arrowLeftPadding = ($('.ui-slider-handle').width()*0.999) - 10;
	
	if(!clientIsIE)
		$('.ui-slider-handle').css("background-position","6px 4px, "+arrowLeftPadding+"px 4px");
	
	
	//$(".ui-handle-helper-parent").css("width","100%");
}

//reset slider value based on scroll content position
function resetValue(){
	
	var remainder = scrollPane.width() - scrollContent.width();
	var leftVal = scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'));
	//alert(leftVal);
	//var percentage = Math.round(leftVal / remainder * 100);
	var percentage = leftVal / remainder * 100;
	
	if(isTouch) {
		//touchScroller.scrollTo(0,0);
	}else{
		scrollbar.slider("value", percentage);
	}
}
//if the slider is 100% and window gets larger, reveal content
function reflowContent(){
	if( (scrollContent.width() - scrollPane.width()) > 0 ) {
		var showing = scrollContent.width() + parseInt( scrollContent.css('margin-left') );
		var gap = scrollPane.width() - showing;
		if(gap > 0){
			scrollContent.css('margin-left', parseInt( scrollContent.css('margin-left') ) + gap);
		}
	}
}



function toggleDetails(detailID,projectID) {
	var colID = $("#"+detailID).attr('col_id');
	var pos = colID*projColWidth;
	
	//close the previous project
	$("#detail"+openCol).html("");
	
	//assign new selected column and open it
	openCol = colID;
	$('.scroll-content').animate({ 'margin-left' :  pos * -1 }, 500);
	$("#"+detailID).html("<img src='resources/images/sample.png'  width='500' height='300' />");
	$("#"+detailID).show();

}
function updateScroll() {
	
	if(isTouch) {
		resetValue();
		touchScroller.setupScroller();
	}else {	
		resetValue();
		sizeScrollbar();
		reflowContent();
	}
	
}

function refreshNavCategories( workType ) {
	
	//alert(workType);
	$.post(base_url + "ajax/fetchIntersectingCategories/",{    
			workType: workType
			
			}, function(data) { 
					
				if ( data.success == "true") {
					
					//alert('success');
					//alert(data.resultHTML);
					
					$('#clientTypesMenu').html(data.resultHTML);
				
				}
				
			},'json');
			
		
}

function loadArticles(ajaxMethod,offset,perPage,workType,clientType,sortType,mode,searchText,articleToLoad) {
	
	//alert(loadedArticles+" of "+totalArticles);
		
	
	if( mode=='reset' ) {
		loadedArticles = 0;
		
		$('#projectsGridHolder').html("");
		$('#newBizHolder').html("");
		
		if(selectedArticleIndex != -1)
			closeArticle();
		
	}
	
	if (loadedArticles <= (totalArticles - 1) ) {
		
		loadingArticles = true;
		
		$('#loadingStatusBar').fadeIn(200);	
		
	
				
		$.post(base_url + "ajax/"+ajaxMethod+"/",{    
			offset: offset,
			perPage: perPage,
			loadedArticles: loadedArticles,
			workType: workType,
			clientType: clientType,
			sortType: sortType,
			searchText: searchText,
			featuredOnPage:featuredOnPage,
			featuredAlreadyLoaded:featuredLoaded,
			limitToMapping: limitProjectsToMapping
			}, function(data) { 
				
				if ( data.success == "true") {
					featuredLoaded += data.featuredIDs;
					//alert(featuredLoaded);
					//console.log(data.debug);
										
					if(searchText && loadedArticles < projectsOnNewPage)
						$('#resultLabel').append(searchText);
						
					if(ajaxMethod == "fetchOffices") {
						$('#projectsHolder').css("height","500px");
					}
	
					//if(mode=='reset') 
						//$('#projectsGridHolder').html(data.resultHTML);
					//else
						$('#projectsGridHolder').append(data.resultHTML);
						
					if( mode=='reset' )
						totalArticles = parseInt(data.totalResults);
					
					//alert(parseInt(data.numResults)/numArticleRows);
					//alert( ((loadedArticles)/numArticleRows)%1 );
					
					reflowColumns();
					
					var addedWidth = ( (loadedArticles/numArticleRows)%1 == 0 ) ? (Math.ceil(parseInt(data.numResults)/numArticleRows)) * projColWidth : (Math.ceil(parseInt(data.numResults)/numArticleRows)-1) * projColWidth;
										
					addedWidth += ( currentSection == "search" ) ? searchMetaColumnWidth : 0;  //if search, add width of 1st column

					
					if(mode=='reset') {
						$('.scroll-content').width( addedWidth );
						$('.scroll-content').css('margin-left',0);
					}
					else {
						$('.scroll-content').width( $('.scroll-content').width() + addedWidth );
					}
															
					//update the sort prompts with non-slug titles
					if(ajaxMethod == "fetchProjects") {
						
						$('#workPrompt').html( data.workSortTitle+'<span class="sf-sub-indicator"> Ž</span>' );
						$('#clientPrompt').html("for "+data.clientSortTitle+'<span class="sf-sub-indicator"> Ž</span>' );
						$('#sortPrompt').html("sorted "+data.sortTitle+'<span class="sf-sub-indicator"> Ž</span>' );	
																		
						adjustNavLayout();
					}		
					
					//show the new biz pitch if applicable
					if( data.newBizMessage != "" ) {
						$('#newBizHolder').html(data.newBizMessage);
						$('#newBizHolder').css("left",(addedWidth+20)+"px");
					}
										
					//if (isTouch)
						//myScroll.refresh();
					//else
						updateScroll();
					
					loadedArticles += parseInt(data.loadedArticles);
					
					if(articleToLoad != undefined) { //for deep linking - load specified article
						
						$('.project').each(function(index) { //force articles to be visible (no fades)
							$(this).css("display","inline-block");
						});
 
						if ( $( 'div[articleid*='+articleToLoad+']' ).attr('index') == undefined) { //desired article hasn't been loaded yet in the grid, load more and try again
							//alert( 'trying again' );
							loadArticles('fetchProjects',loadedArticles,projectsOnNewPage,curWorkType,curClientType, curSortType, '',undefined,curArticleID);
						
						}else { // desired article is in the grid
							loadArticle(0,articleToLoad,ajaxMethod.substr(0,ajaxMethod.length-1),true); //remove 's' from end of ajax method to get the article method	
						}
					}
				}else {
					
					if( numArticleRows == undefined ) {
						$('.scroll-content').height(500);
					}
					
					/* $('#projectsGridHolder').html(data.resultHTML); */
					$('#newBizHolder').css("left","0px");
					
					if( currentSection == "search" )
						$('#searchResultHolder').hide(0);
					
					$('#workPrompt').html( data.workSortTitle+'<span class="sf-sub-indicator"> Ž</span>' );
					$('#clientPrompt').html("for "+data.clientSortTitle+'<span class="sf-sub-indicator"> Ž</span>' );
					
					$('#newBizHolder').html(data.newBizMessage);	
					
					$('.scroll-content').width($('#newBizHolder').width());
					
					updateScroll();
				}
				
				//setTimeout ( function(){loadingArticles = false;}, 2000 );
				
				loadingArticles = false;
				$('#loadingStatusBar').fadeOut('fast');
				
		},'json');
		
	}else {
		//alert('no more articles to load');
	}
}


function loadArticle(index,id,ajaxMethod,fromDeepLink) {
	
	fromDeepLink = ( fromDeepLink == undefined ) ? false : fromDeepLink;
	
	if(selectedArticleIndex != -1) {
		closeArticle();
		//refreshOnURLChange = true;
	}
	
	if(loadingArticles){
		
		setTimeout(function(){loadArticle(index,id,ajaxMethod,fromDeepLink)},500);
		
	}else {
	
		$.post(base_url + "ajax/"+ajaxMethod+"/",{    
			id: id
			}, function(data) {  
				
				//alert($.address.parameter(0));
				
				//alert(articleHeight*numArticleRows);
				articleIsLoaded = true;
				
				$("#articleDetail").html(data.resultHTML);
				
				if ( ajaxMethod == "fetchPartner" )
					$("#articleDetail").fadeIn(1200);				
				else
					$("#articleDetail").show();
				
				//alert($("#articleDetail").width());
	
				//if ( ajaxMethod == "fetchPartner" )	
					//$('#articleDetail').columnize({ width:300, height: (articleHeight*numArticleRows - 80), buildOnce: true });
				//selectedArticleIndex = index;
				
				//selectedArticleIndex = parseInt( $('#'+id).attr('index') );
				selectedArticleIndex = parseInt( $( 'div[articleid*='+id+']' ).attr('index') );
			
				
				//alert(selectedArticleIndex);
				var offsetWidth =  $("#articleDetail").width() + 40;
				
				var col = Math.ceil((selectedArticleIndex+1)/numArticleRows);
				var offsetIndex = (col * numArticleRows) - 1;
				var colOffset;
				
				
				//alert($('.scroll-content').width());
				//if (ajaxMethod == "fetchPartner")
					//$('.partnersDetail').css("width",offsetWidth);
	
				$('.scroll-content').width( $('.scroll-content').width() + offsetWidth );
				//alert(offsetIndex);
				//alert($('#281').)
				var listItem = $('#281');
				//alert('Index: ' + $('.project').index(listItem) + " of " + offsetIndex);
				
				$('.project:gt('+offsetIndex+')').each(function(index) {
					
					colOffset = parseFloat( $(this).css("left") ) + offsetWidth;
					//console.log("index: "+ $(this).attr("index") +", id: "+ $(this).attr("id"));
						
						
					if(fromDeepLink) {
						
						$(this).css("left",  colOffset  );
					 }else {
						$(this).animate({"left":  colOffset  },1200);	
					}
				});
				
				var articleMoveTo = ( currentSection == "search" ) ? (col*projColWidth)+searchMetaColumnWidth : (col*projColWidth);
			
				$("#articleDetail").css("left",articleMoveTo);
				
				
				
				
							
				$("#pageTitle").html(data.title);
				$("#totalImages").html(data.numMedia);
				$("#pageHeader").show();
				
				//var newScrollWidth = $("#"+detailID).width() + $("#projectsHolder").width();
				
				//$("#projectsHolder").css("width",  newScrollWidth+"px" );
					
				//scrollbar.slider("value", (col * projColWidth / $('.scroll-content').width())*100 );	
				
				//alert((col * projColWidth * -1)-17);
				if (!isTouch) {
					var contentViewDifference = $('.scroll-content').width() - $('.scroll-pane').width();
					var scrollTo = ( currentSection == "search" ) ?  (col * projColWidth)+16+searchMetaColumnWidth : (col * projColWidth)+16;
				
					if( contentViewDifference > scrollTo ) {
						
						$('.scroll-content').animate({ 'margin-left' :  scrollTo*-1 }, 
							800, 
							function() {
			    				resetValue();
								sizeScrollbar();
			  				});	
			  		}else { //if scrollto puts scroll area beyond maximum, just scroll to the max
			  			$('.scroll-content').animate({ 'margin-left' :  contentViewDifference*-1 }, 
							800, 
							function() {
			    				resetValue();
								sizeScrollbar();
			  				});
			  		
			  		}		
			  	}else {
			  		touchScroller.setupScroller();
			  	
			  	}				
				
			},'json');
		}
}

function closeArticle(animate) {

	//var newScrollWidth = $("#projectsHolder").width() - $("#detail"+openCol).width();
	//$("#projectsHolder").css("width",  newScrollWidth+"px" );
	
	refreshOnURLChange = false;
	var params = $.address.pathNames();
	if ( currentSection == "work" || currentSection == "selectedWork" )
		$.address.path( params[0]+'/'+params[1]+'/'+params[2]+'/' );
	else
		$.address.path( '/' );
	
	articleIsLoaded = false;
	
	var offsetWidth =  $("#articleDetail").width() + 40;
	var col = Math.ceil((selectedArticleIndex+1)/numArticleRows);
	var offsetIndex = (col * numArticleRows) - 1;
	var pos;

	//scroll back to the beginning
	
	var contentViewDifference = scrollContent.width() - offsetWidth;
	
	//alert(scrollContent.width() - scrollPane.width());
	//if( (scrollContent.width() - scrollPane.width()) > 0 )
	if( contentViewDifference > scrollPane.width() )
		pos = (col-1)*projColWidth;
	else
		pos = 0;

	
	if(!isTouch) {		
		if (animate == true) {
			$('.scroll-content').animate({ 'margin-left' :  pos * -1 }, 1000, function() { updateScroll(); });
		} else {
			$('.scroll-content').css('margin-left',pos * -1);
			updateScroll();
		}
	}
	//remove content
	if (animate == true) {
		$("#pageHeader").fadeOut(500);
		$("#articleDetail").fadeOut(1000,function(){
			$("#articleDetail").html("");
		});
	} else {
		$("#pageHeader").hide(); $("#articleDetail").hide(); $("#articleDetail").html("");
	}	
	
	
	//slide the older projects back
	var resetVal;
	
	$('.project:gt('+offsetIndex+')').each(function(index) {
	
		if (animate == true) {
			resetVal = parseFloat( $(this).css("left") ) - offsetWidth;
			$(this).delay(100).animate({"left": resetVal},1000);
		} else {
			$(this).css("left", function(index, value) {
		    	return parseFloat(value) - offsetWidth;
		    });
		}
		
	});
	
	
	if (animate == true)
		$('.scroll-content').delay(1100).width( $('.scroll-content').width() - offsetWidth );
	else
		$('.scroll-content').width( $('.scroll-content').width() - offsetWidth );
	
	selectedArticleIndex = -1;
	slideshowCurIndex = 0;
	$('#currentImage').html( "1" );
	
	
}

function toggleAbout() {
	
	if( $('#aboutHolder').css('display') == "none" ) { //show it
		$('#aboutHolder').fadeIn(0);
		$('#aboutHolder').animate({"left": 0},800, "easeOutExpo" );
		
	}else {
		$('#aboutHolder').animate({"left": -500},500 );
		$('#aboutHolder').delay(500).fadeOut(0);
	}
	
	
	//$('#aboutHolder').toggle('fast');

}
function handleArticleLink (id) {
	
	if ( selectedArticleIndex != -1 ) {
		closeArticle();
		$.address.path($.address.path()+id+'/');
		
	} else {
		//if id already in url, but project was not loaded, clear the old before appending the new
		refreshOnURLChange = false;
		var params = $.address.pathNames();
		if ( currentSection == "work" || currentSection == "selectedWork" )
			$.address.path( params[0]+'/'+params[1]+'/'+params[2]+'/' );
		else
			$.address.path( '/' );
		refreshOnURLChange = true;
	
		$.address.path($.address.path()+id+'/');
	}

}



