$(document).ready(function(){
	
	// ######## Global vars ########
	
	var gridunit = 20;
	var portfolioht = 16;
	var portfoliowd = 16;
	var fselsize = 96;
	var portfoliospacing = 3;
	var openspeed = 300;
	var closespeed = 250;
	
	var col0open = false;
	var propen = false;
	
	var prmode = false;
	
	var col1open = false;
	var aboutopen = false;
	
	var scoffsets = new Array();
	var fselfullres = new Array();
	var sccopy = new Array();
	
	var proffsets = new Array();
	var prcopy = new Array();
	var prtitles = new Array();
	
	var prnav = '';
	
	// ######## Global strings ########
	
	var pswitchstrings = ['View full portfolio','View showcase'];
	
	
	// ######## XML load and init ########
	
	 $.ajax({
	    type: "GET",
	    url: "sitecontent/",
	    dataType: "xml",
	    success: parseXML
	});
	
	function parseXML(xml){
		
		// #### Render Showcase ####
		$('div#showcase').append('<a href="javascript:void(0);" id="fclose" class="closebutton">Close</a>');
		$('a#fclose').hide();
		var sc ="";
		$(xml).find("feature").each(function(){
			// which one are we?
			var findex = $(this).index();
			
			// what's our path?
			// not needed in dynamic version
			var mypath = $(this).attr('fpath');
			
			// instead, we just get the full path to the splash image
			var splashpath = $(this).attr('splashimage');
			
			// set up each showcase box in a render string
			
			// add copy to copy array
			var headlinepluscopy = '<h3>'+$(this).attr("ftitle")+'</h3>';
			headlinepluscopy += $(this).children('featurecopy').text();
			sccopy.push(headlinepluscopy);
			// add offsets to scoffsets array
			var coords = [$(this).attr('xcrop'),$(this).attr('ycrop')];
			scoffsets.push(coords);
			
			sc += '<div class="showcasebox">'; // the masking container
			sc += '<div class="showcaseview">'; // the full view inside
			sc += '<div class="rollcard"><p>'+$(this).attr("ftitle")+'</p></div>'; // the overlay card
			// add the main image
			sc += '<img class="splash" src="'+splashpath+'">';
			// add the placeholder image
			sc += '<img class="featured" src="'+splashpath+'">';
			//sc += '<img src="fimages/'+$(this).attr('fpath')+'/'+$(this).find('featurepic').first().attr('fullres')+'">';				
			// add the feature selects
			sc += '<ul class="fselbank">'
			var fullrespaths = [];
			
			$(this).find('featurepic').each(function(){
				sc += '<li class="fselect">';
				// add rollcard
				sc += '<div class="rollcard mini">'+$(this).attr('fstitle')+'</div>';
				// add thumbnail image
				sc += '<img src="'+$(this).attr('thumb')+'" width="96px" height="96px"></li>';
				// add fullres path to fselfullres array
				fullrespaths.push($(this).attr('fullres'));
			});
			
			fselfullres.push(fullrespaths);
			sc += '</ul></div><p class="credit">';
			if ($(this).attr('copyright')!=""){				
				sc += '&copy '+$(this).attr('copyright');
			} else {
				sc += 'Some work we\'ve done for '+$(this).attr('ftitle');
			}
			sc += '</p></div>';
		});	
		$("#showcase").append(sc);	
		// TEMP auto roll-up showcase so we can work on portfolio
		//$('div.showcasebox').slideUp(0);
		//prmode = true;
		//console.log("fselfullres = "+fselfullres);
		//console.log(sccopy);
		// add perm values
		//$('div.showcasebox').data('layoutvars', {offsets:scoffsets[$(this).index(),0]});
		
		
		
		// #### Render Portfolio ####
		
		var pr = '';
		prnav += '<h3>categories</h3><ul>';
		$(xml).find('medium').each(function(){
			var thismedium = $(this).attr('mtitle');
			var thisanchor = thismedium.split(' ').join('_');
			prnav += '<li><a href="javascript:void(0)">'+thismedium+'</a></li>';
			// removed anchor version to avoid hash pollution
			//prnav += '<li><a href="#'+thisanchor+'">'+thismedium+'</a></li>';
			pr += '<a name="'+thisanchor+'" class="hashtarg"><h4>'+thismedium+'</h4></a>';
			pr += '<ul>';
			// iterate through portfolio items in this medium
			$(xml).find('project[medium="'+thismedium+'"]').each(function(){
				// which one
				var pindex = $(this).index();
				
				// add offsets to array
				var thisx = $(this).attr('xcrop');
				var thisy = $(this).attr('ycrop');
				var theseoffsets = [];
				theseoffsets.push(thisx, thisy);
				proffsets.push(theseoffsets);
				
				// add copy to array
				prcopy.push($(this).text());
				prtitles.push($(this).attr('ptitle'));
				
				pr += '<li class="portfoliobox">';
				pr += '<img src="'+$(this).attr('imagefile')+'" style="top:-'+thisy+'px;left:-'+thisx+'px;">';
				pr += '<div class="rollcard">'+$(this).attr('ptitle')+'</div>';
				pr += '</li>';
				
			});
			pr += '</ul>';
			
			
		});
		prnav += '</ul>';
		$('#portfolio').append(pr);
		$('div#displaycopy').html(prnav);
		
		// roll up the portfolio and the nav
		$('div#portfolio').slideUp(0);
		$('div#displaycopy').slideUp(0);
		
		// ####
		
		
		initBasic();
	}
	
	// ######## Basic page interaction ########
	
	function initBasic(){
		
		// sync column heights
		function syncColHeights(){
			// let's not, for now
			/*
			var pradditionalheight = 0;
			if (prmode==true){
				pradditionalheight = 250;
			};
			$('div.column').not('div#showcase').animate({height:$('div#showcase').height()+pradditionalheight},openspeed);
			console.log('synced?');
			*/
		}
		
			// remove fixed height from passed element
		
		function unlockHeight(unlockee){
			//unlockee.css({'height': ''});
			$('div.column').css({'height': ''});
		}
		
		// instead, getting this snippet from buildinternet.com
		function syncHeights()  {  
			unlockHeight();
			 var tallestcolumn = 0;  
			 $('div.column').each(function()  {  
				 currentHeight = $(this).height();  
				 if(currentHeight > tallestcolumn)  {  
					 tallestcolumn  = currentHeight;  
				 }  
			 });  
			 $('div.column').height(tallestcolumn);  			 
		} 
		
	
		
		// open first column
		function openCol0(){	
			if (col1open==true){
				closeCol1();
			}
			col0open = true;
			// open the column up
			unlockHeight($('div#showcase'));
			$('div#showcase').animate({
				width:560
			}, openspeed, syncHeights);
			// if we were in showcase and not portfolio
			if (prmode == false){
				// enable the close button
				$('a#fclose').show();
			}
			// make the page bigger
			$('div#container').animate({width:1200}, openspeed);
			
			// hide intro
			$('div#intro').stop(true, true).slideUp(openspeed);
			
		}
		
		function closeCol0(special){
			var endwidth = 340;
			// are we closing col0 further than normal? (col1 opened)
			if (special == 'alltheway'){
				endwidth = 128;
			}
			// hide close button 
			$('a#fclose').hide();
			col0open = false;
			// close the column
			unlockHeight($('div#showcase'));
			$('div#showcase').stop(true).animate({
				width:endwidth
			}, openspeed, syncHeights);
						
			// if we were in showcase and not portfolio
			if (prmode == false){
				// close any showcase boxes that are open
				$('div.showcasebox').stop(true).animate({
					width:endwidth,
					height:120,
					'margin-top':20
				}, openspeed, function(){syncColHeights();});
				// return the rest of the boxes
				//$('div.showcasebox').slideDown(openspeed);
				// remove selection from any fselects in showcase
				$('div.showcasebox').find('div.rollcard').removeClass('miniselected');
				// hide the viewer image
				$('img.featured').hide();
				// clear left text
				$('div#displaycopy').slideUp(openspeed, function(){$('div#displaycopy').html(prnav);});
				// show intro
				$('div#intro').stop(true, true).slideDown(openspeed);
			} else {
				// just show the portfolio nav
				$('div#displaycopy').html(prnav);
				reInitPortfolioAnchors()
			}
			
			// back to smaller container
			$('div#container').animate({width:1000}, openspeed);
			offsetShowcase('animate');

		}
		
		function openCol1(){
			if (prmode==true){
				$('a#portfolioswitch').click();
			}
			if (col0open==true){
				closeCol0('alltheway');
			}
			$('a#portfolioswitch').hide();
			col1open = true;
			// shift column sizes
			unlockHeight($('div#aboutus'));
			$('div#showcase').stop(true).animate({
				width:128
			}, openspeed);
			$('div.showcasebox').stop(true).animate({
				width:128,
				height:120,
				'margin-top':20
			}, openspeed);
			$('div.showcasebox div.rollcard').not('.mini').stop(true).animate({
				width:88
			}, openspeed);
			$('div#aboutus').animate({
				width:340
			}, openspeed, syncHeights);
			// show close button
			$('a#aclose').show();
			// hide intro
			$('div#intro').stop(true, true).slideUp(openspeed);
			
		}
		
		function closeCol1(special){
			var endwidth = 340;
			if (special == 'alltheway'){
				endwidth = 560;
			}
			col1open = false;
			$('a#portfolioswitch').show();
			// shift column sizes
			unlockHeight($('div#aboutus'));
			$('div#showcase').animate({
				width:endwidth
			}, openspeed);
			$('div.showcasebox').animate({
				width:endwidth
			}, openspeed);
			$('div.showcasebox div.rollcard').not('.mini').animate({
				width:300
			}, openspeed);
			$('div#aboutus').animate({
				width:128
			}, openspeed, syncHeights);
			// close any open panels
			$('div#aboutus div.open').each(function(){
				$(this).slideUp(openspeed);
				$(this).removeClass('open');
			});
			// hide close button
			$('a#aclose').hide();
			// show intro
			$('div#intro').stop(true, true).slideDown(openspeed);
		}
		
		// make offsets for showcase
		function offsetShowcase(animateornot){
			if (animateornot=='animate'){
				var myspeed = openspeed;
			} else {
				var myspeed = 0;
			}
			$('div.showcasebox').find('img.splash').each(function(){
				//console.log($(this).parent().index('div.showcasebox'));
				var myindex = $(this).parent().parent().index('div.showcasebox');
				$(this).animate({
					'margin-top':0-parseInt(scoffsets[myindex][1]),
					'margin-left':0-parseInt(scoffsets[myindex][0])
					}, myspeed);
			});
		}		
		// and do it once
		offsetShowcase();
		
		// portfolio switch interaction
		$('a#portfolioswitch').click(function(){
			// is showcase open?
			if (col0open==true){
				// then close it first
				closeCol0();
			}
			// are we not in portfolio mode?
			if (prmode==false){
				prmode = true;
				// change text and add class to change icon
				$(this).text(pswitchstrings[1]);
				$(this).addClass('open');
				// show fcopy
				$('div#displaycopy').html(prnav);
				reInitPortfolioAnchors()
				//console.log("prnav = "+prnav);
				$('div#displaycopy').slideDown(openspeed);
				// hide all the showcaseboxes and show the portfolio
				unlockHeight($('div#showcase'));
				$('div.showcasebox').slideUp(openspeed);
				$('div#portfolio').slideDown(openspeed, function(){syncHeights();});
				// change heading to read 'portfolio'
				$('#showcase h2').text('portfolio');	
				// hide intro
				$('div#intro').stop(true, true).slideUp(openspeed);			
			} else {
				// is a portfolio box open?
				if (propen==true){
					// run close function on specific box
					$('div#portfolio').find('li.open').closePortfolioBox();
				}
				// change text and remove open class
				$(this).text(pswitchstrings[0]);
				$(this).removeClass('open');
				prmode = false;
				// hide the portfolio and show all the showcaseboxes
				unlockHeight($('div#showcase'));
				$('div#portfolio').slideUp(openspeed, function(){syncHeights();});
				$('div.showcasebox').slideDown(openspeed, function(){syncHeights();});
				// close displaycopy
				$('div#displaycopy').slideUp(openspeed, function(){
					// move the fcopy back to its normal position
					$('div#displaycopy').css({'margin-top':0})
				});
				// change heading back
				$('#showcase h2').text('showcase');
				// show intro
				$('div#intro').stop(true, true).slideDown(openspeed);
			}
		});
	
		// ######## Showcase interaction ########
			
		// rollcard display/hiding
		$('div.showcasebox').mouseenter(function() {
			if (col0open == false){
				$(this).find('div.rollcard').show();
			}
		});
		
		$('div.showcasebox').mouseleave(function() {
			if (col0open == false){
				$(this).find('div.rollcard').hide();
			}
		});
		
		// showcase close button interaction
		$('a#fclose').click(function(){
			closeCol0();
		});
		
		// expand showcase on click
		$('div.showcasebox').click(function() {
			if (col0open == false){
				$(this).find('div.rollcard').hide();
			}
			if (col1open == true){
				closeCol1('alltheway');
			}
			$(this).stop(true, true).animate({
				width:560,
				height:450
			}, openspeed, function(){syncColHeights();});
			
			$(this).siblings('.showcasebox').stop(true, true).animate({
				'height':0, 'margin-top':0}, openspeed);
			openCol0();
			
			// show left-column copy and give it text
			$('div#displaycopy').html(sccopy[$(this).index('div.showcasebox')]);
			$('div#displaycopy').slideDown(openspeed);
			
			// realign the splash images
			$(this).find('img.splash').animate({
				'margin-top':0,
				'margin-left':0
			}, openspeed);
			
		});
		
		// #### Featureselect interaction ####
		
		$('div.showcasebox').find('li.fselect').mouseenter(function(){
			// show rollcard
			$(this).children('div.rollcard').show();
		});
		
		$('div.showcasebox').find('li.fselect').mouseleave(function(){
			// show rollcard
			$(this).children('div.rollcard:not(.miniselected)').hide();
		});
		
		$('div.showcasebox').find('li.fselect').click(function(){
			// change rollcard class
			//$(this).children('div.rollcard').show(); //make it come back if it left
			$(this).siblings().children('div.rollcard').removeClass('miniselected');
			$(this).siblings().children('div.rollcard').hide();
			$(this).children('div.rollcard').addClass('miniselected');
			scindex = parseInt($(this).parent().parent().parent().index('div.showcasebox'));
			fsindex = $(this).index();
			// replace image
			$(this).parent().parent().find('img.featured').show();
			$(this).parent().parent().find('img.featured').attr('src', fselfullres[scindex][fsindex]);
			//console.log(scindex+" and "+fsindex+" make "+fselfullres[scindex][fsindex]);
			
		});
		
		// ######## Portfolio interaction ########
		
		$('div#portfolio').find('li.portfoliobox').mouseenter(function(){
			if (propen == false){
				$(this).children('div.rollcard').show();
			}
		});
		
		$('div#portfolio').find('li.portfoliobox').mouseleave(function(){
			$(this).children('div.rollcard').hide();
		});
		
		$('div#portfolio').find('li.portfoliobox').click(function(){
			// handy index var for this element
			var thisindex = $(this).index('div#portfolio li');
			if (propen == false){
				// mark this one for closing
				$(this).addClass('open');
				propen = true;				
				$(this).children('div.rollcard').hide();
				openCol0();
				// make this one big
				$(this).animate({width:320,height:320}, openspeed);
				// make the mid-container big
				$('div#portfolio').animate({width:580}, openspeed);
				// move the image into place
				$(this).find('img').animate({'top':0,'left':0}, openspeed);
				// margin out the others
				// set the reference positions for the each function
				var refx = $(this).position().left;
				var refy = $(this).position().top;
				//console.log('reference is '+refx+','+refy+' for number '+$(this).index());
				$('li.portfoliobox').not($(this)).each(function(){
					// animate the margins
					if ($(this).position().left == refx){
						//console.log('got one at '+$(this).position().left+'; this one is '+$(this).index());
						$(this).animate({'margin-right':240,'opacity':.33}, openspeed);
					}
					if ($(this).position().top == refy){
						$(this).animate({'margin-bottom':240,'opacity':.33}, openspeed);
					} else {
						$(this).animate({'opacity':.33}, openspeed);
					}
				});
				// move the text down here
				var myyoffset = $(this).offset().top;
				$('div#displaycopy').animate({'margin-top':myyoffset-180}, openspeed);
				// show left-column copy and give it text
				$('div#displaycopy').slideDown(openspeed);
				var displaytext = '<h3>'+prtitles[thisindex]+'</h3>';
				displaytext += prcopy[thisindex];
				$('div#displaycopy').html(displaytext);
				
				// show portfolio closer and position it
				$('a#prclose').show();
				$('a#prclose').css({'top':refy,'left':refx});
			} else {
				$('a#prclose').click();
			}
		});
		
		$('a#prclose').click(function(){
			// run close function on specific box
			$('div#portfolio').find('li.open').closePortfolioBox();			
		});
		//$('div#portfolio').find('li.portfoliobox').function
		
		// close function		
		jQuery.fn.closePortfolioBox = function() {
			// repeated from other function
			var thisindex = $(this).index('div#portfolio li');
			
			closeCol0();
			// make this one small
			$(this).animate({width:100,height:100}, openspeed);
			// move the image back
			var origx = proffsets[thisindex][0];
			var origy = proffsets[thisindex][1];
			$(this).find('img').animate({'top':0-origy,'left':0-origx}, openspeed, function(){propen = false;});
			$('li.portfoliobox').not($(this)).each(function(){
				// animate the margins
				//if ($(this).position().left == refx){
					$(this).animate({'margin-right':20,'margin-bottom':20,'opacity':1}, openspeed);
				//}
			});
			// shrink the portfolio mid-container
			$('div#portfolio').animate({width:360}, openspeed);
			
			// hide portfolio closer
			$('a#prclose').hide();
			// unmark
			$(this).removeClass('open');
		};		
		
		// anchor navigation through portfolio
		// this must be done every time we enter portfolio mode because we constantly change the contents of div#displaycopy
		
		function reInitPortfolioAnchors(){
			$('div#displaycopy li a').click(function(){
				//var hashtarg = $(this).attr('href');
				var myeq = $(this).parent().index();
				//console.log("eq is "+myeq);
				var ycoord = $('div#portfolio a h4').eq(myeq).offset();
				//console.log("ycoord = "+ycoord.top);
				$('div#displaycopy').animate({'margin-top':ycoord.top-144}, openspeed);
				// go there in the browser
				window.scrollTo(0,ycoord.top-20);
			});
		}
		
		// ######## About Panel interaction #######
		
		$('a#aclose').hide();
		
		$('a#aclose').click(function(){
			closeCol1();
		});
		
		$('div#aboutus li a').click(function(){
			aboutopen = true;
			// slide down siblings
			unlockHeight($('div#aboutus'));
			$(this).parent().siblings().find('div.open').each(function(){
				$(this).slideUp(openspeed);
				$(this).removeClass('open');
			});
			// mark it as open
			$(this).siblings().addClass('open');
			$(this).siblings().slideDown(openspeed, syncHeights);
			openCol1();
		});
				
		// ######## Things to do once that don't fit anywhere else ########
		
		// hide rollcards
		$('div.rollcard').hide();
		// hide the portfolio closer
		$('a#prclose').hide();
		// hide the about panels
		$('div.column ul').show();
		$('div.aboutpanel').slideUp(0);
		syncColHeights();
		syncHeights();
						
		// show only the first one
		//$('div.showcasebox li.fullres').hide();
		//$('div.showcasebox li.fullres').eq(0).show();
	
	}
	
});
