// ** This whole thing is so slow in IE6 that it's pretty much non-functional.  I suggest replacing with a static gallery in IE6  ** //

// Variables used through the functions //

// Tell the script the dimensions of the box (Actual box dimensions must be set in CSS, this is just for the grid positioning )
var boxwidth = 110;
var boxheight = 80;
// size of the box on hover
var exW = 115;
var exH = 84;
// space to the top and left of each box
var space = 8;
// minimum dimensions for the box on click.
var fullW = 200;
var fullH = 100;

// dimensions of the grid container.  Height is *minimum* height the container should be.  Script will resize it if need be.
var conH = 456;
var conW = 610;

// default filter
var d_filter = (typeof(d_filter)!='undefined')?d_filter:'internet';

// calculate the difference between the box size, and the hover size
var	difH = ((exH-boxheight)/2);	
var difW = ((exW-boxwidth)/2);

// this re-positions boxes into a grid
// this can be rather resource intensive when there are a lot of boxes on the screen.  Call this as rarely as needed.
// ** TODO: Write a function to re-position a single box in the grid, so that we don't have to do the whole thing when a box is collapsed ** //
this.grid = function(){	

	// 'box' is apparently a reserved variable in ie.  redeclare to avoid error
	var box;
	var async;
	var pres;
	var boxes;
	var container;
	var num;
	var cols;
	var skip;
	
	// get optional arguments //
	// position boxes by top and left at the same time(true), or by left and then top(false)
	async = (arguments.length > 0)?arguments[0]:false;
	// preserve clicked boxes.  grid() is called when a box is collapsed, so this stops grid() from collapsing any expanding boxes
	pres = (arguments.length > 1)?arguments[1]:false;
	
	// get the grid container and all boxes
	boxes = $("#grid .box");
	container = $("#grid");

	// number of boxes
	num = boxes.length;
	
	// compute columns
	cols = Math.floor(container.width()/((boxwidth+space)));
	row = 0;
			
	// loop through boxes
	skip = 0;
	for( x = 0; x < num; x++ ) {

		// get current box
		box = boxes.eq(x);
		
		// check if the box is shown
		if( box.css("display") == "none" ) {
			
			// if not, count it\
			skip++;
			continue;
		
		}
		
		if( box.contents().filter("a.js_no") ) {
			box.prepend(box.contents().filter("a.js_no").html());
			box.contents().filter("a.js_no").remove();
		}
		
		// adjust order for skipped boxes
		ord = x-skip;
		
		// calculate the row and column
		row = (Math.ceil((ord+1)/cols)-1);
		col = ord%cols;
		
		// if we aren't preserving expanded boxes, collapse any that are open
		if( !pres ) {
			if( box.hasClass("clicked")) {
				box.trigger("click").trigger("mouseleave");
				continue;
			}
		}
		
		// position boxes which aren't clicked, and aren't hovered over while preserve is true
		if( !box.hasClass("clicked") && !(box.hasClass("hovered")&&pres) ) {
			
			// animate async or not
			if( async && box.position().left != 0 ) {
				box.animate({left: ((col*boxwidth)+(col*space)+space)+"px", top: ((row*boxheight)+(row*space)+space)+"px"});
			} else {
				box.animate({left: ((col*boxwidth)+(col*space)+space)+"px"}).animate({top: ((row*boxheight)+(row*space)+space)+"px"});					
			}
		}
	}
	
	// check how big the grid *should* be
	newHe = (((row+1)*boxheight)+((row+4)*space));
	
	// grow grid if you need to, but don't go smaller than specified height
	if( newHe > conH ) { 
		box.queue(function(){$("#grid").animate({height: newHe+"px"});box.dequeue()});
	} else {	
		if( $("#grid").height() != conH+8 ) box.queue(function(){$("#grid").animate({height: (conH+8)+"px"});box.dequeue()});
	}
		
};



this.load = function() {

	// reposition box image according to hover difference
	$("#grid .box img").css("margin-left","-"+(difW+1)+"px").css("margin-top","-"+(difH+1)+"px");
	
	// make sure of initial checkbox state
	$("input.filter").removeAttr('checked');
	$("input.checked").attr('checked','true');
	
	// stuff to make page work with js
	$("#grid .box").css({display:"none",left:"0",top:"0",position:"absolute"});
	//$("#grid ."+d_filter).fadeIn();
	if(!(jQuery.browser.msie && (jQuery.browser.version.substr(0,1)=="6"))) $(".show").css("display","inline");
	$("#grid").css("visibility",'visible');
	
	// set the container's height, so we can be sure of reported values
	$("#grid").css("height",(conH+space)+"px").css("width",(conW+space)+"px").css("margin","0 auto");

	// initial grid sort
	//grid(false);

	// click function for checkboxes
	$("input.filter").bind("click", function(e) {
	
		// collapse any open boxes
		$("#grid .clicked").trigger("click").trigger("mouseleave");
				
		// get all checkboxes, and how many
		inputs = $("input.filter");
		num = inputs.length;
		
		str = '';		
		
		// are we fading in or out
		type = this.checked ? "in" : "out";
		
		// loop through inputs
		for( x = 0; x < num; x++ ) {
		
			// is it checked
			if( inputs.eq(x).attr('checked') == true ) {
			
				// build filter string
				if( str != '' ) str += ', ';
				str += '.'+inputs.get(x).id;
			
			}
		}
		
		// get boxes
		boxes = $("#grid "+str);
					
		if(boxes.eq(0).css("display") == "none"){
			boxes_v = $("#grid .box:visible");
			boxes_v.fadeOut();
			
			// fade boxes in
			boxes = boxes.filter(":hidden");
			boxes.css("visibility","hidden");
			
			if( boxes_v.length >= 1 ) {
				
				last = boxes_v.filter(":last");
				
				last.queue(function(){boxes.fadeIn();last.dequeue();});
				last.queue(function(){setTimeout("grid(true)",500);last.dequeue();});
			} else {
				
				boxes.fadeIn();
				last = boxes.filter(":last");
				last.queue(function(){grid(false);last.dequeue();});
			}
			
			boxes.css("visibility","visible");			
		} else {
			
		}	
		
		
	});
	
	// fade in all checked filters
	/**** 
		Careful, this triggers grid() as well, so it may cause resource death if 
		there is more than one checked and there is a lot of boxes  
	****/
	// ** TODO: Write a pre-loader.  Calling grid() while a page is loading generally looks like ass when there is a fair amount of boxes visible.
	$("input.filter:checked").triggerHandler('click');
	
	
	// function for hover
	function boxHover(e) {
	
		// don't do the hover effect in IE, it looks stupid.
		if( !jQuery.browser.msie ) {
		
			// don't do whatever it was you wanted to do
			e.preventDefault();
		
			// a) don't hover if there is stuff in the queue (this fixes something, I know it does)
			// b) don't hover if already hovered	
			if( $(this).queue().length == 0 && !$(this).hasClass("hovered")){
			
				// add class so we can track hovered boxes
				$(this).addClass("hovered");
				
				// the z-index is kind of redundant at this point, but if the hovers are going to overlap, it should be higher to make sure the hovered box is on top
				// also, animate
				$(this)
					.css("z-index",1)
					.animate({top: "-="+difH+"px", left: "-="+difW+"px", height: exH+"px", width: exW+"px"},80);
					
				// move the image inside to show more, but still hiding the border
				// when the grid is not aligned to the left edge, the image can kind of jitter.  Currently should look right in 1024x768.
				$(this).contents().filter("img")
					.animate({marginTop:"-1px",marginLeft:"-1px"},80);
					
				// this changes the z-index back to where you want it after the hover animation is done, in case hovers overlap.
				//$(this).queue(function(){$(this).css("z-index",2);$(this).dequeue();});
			}
		}
	}
	
	
	// function to un-hover
	function boxUnhover(e) {
	
		// don't do hover in IE, it looks dumb.
		if( !jQuery.browser.msie ) {
		
			// don't not hover.
			e.preventDefault();
			
			// only unhover stuff that has been hovered.
			if( $(this).hasClass("hovered") ) {
			
				// animate
				$(this).animate({top: "+="+difH+"px", left: "+="+difW+"px", height: boxheight+"px", width: boxwidth+"px"},80);
				
				// move image back
				$(this).contents().filter("img")
					.animate({marginTop:"-"+(difH+1)+"px",marginLeft:"-"+(difW+1)+"px"},80);
				
				// shove it back on the z-index
				$(this).queue(function(){$(this).css("z-index",0);$(this).dequeue();});
				
				// take off hovered tag
				$(this).removeClass("hovered");
			}
		}
	}
	
	xOffset = -10;
	yOffset = 10;
	
	// simulate hover effect on the filter labels
	$(".filter_label").hover(function(e) {
		if( !$(this).hasClass("filter_clicked") ) $(this).css("background","url('graphics/btn_ul.jpg') bottom left no-repeat");
		$(".portfolio_table .hidden").hide();	 
		$("#hover_"+$(this).attr("for"))
			.css("z-index",100)
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
			
		
	},function() {
		if( !$(this).hasClass("filter_clicked") ) $(this).css("background","none");
		
		$("#hover_"+$(this).attr("for")).fadeOut();
		
	});
	$(".filter_label").mousemove(function(e){
		$("#hover_"+$(this).attr("for"))
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});	
	
	// click effect on the filter labels
	$(".filter_label").click(function() {
			$(".filter_label").removeClass("filter_clicked");
			$(".filter_label").css("background","none");
			$(".filter_label").contents().filter(".top").css("background","none");
			$(".filter_label").contents().filter(".top").contents().filter(".bottom").css("background","none");
			
			$(this).addClass("filter_clicked");
			$(this).css("background","url('graphics/btn_bg_rpt.jpg') top left repeat-y");
			$(this).contents().filter(".top").css("background","url('graphics/btn_bg_t.jpg') top left no-repeat");
			$(this).contents().filter(".top").contents().filter(".bottom").css("background","url('graphics/btn_bg_b.jpg') bottom left no-repeat");
			$("#"+$(this).attr("for")).trigger('click');
		
	});
	$("input.checked").siblings().filter("label").triggerHandler("click");
		
	// bind hover functions to boxes
	$("#grid .box").bind("mouseleave",boxUnhover).bind("mouseenter", boxHover);
	
	// click event for boxes
	$("#grid .box").click(function(e) {
		
		// make sure the browser knows the mouse is inside the box
		$(this).trigger("mouseenter");
		
		// check state 
		// if we need to expand
		if( $(this).width() <= exW ) {
			
			// collapse any open boxes
			$("#grid .clicked").trigger("click").trigger("mouseleave");
						
			// movin' on up
			$(this).css("z-index",5);
			
			// calculate how wide the box should be
			imgW = 458;//($(this).children().filter("img").outerWidth())-2;
			newW = (fullW>imgW?fullW:imgW);
			$(this).contents().filter(".span").css("width",newW);
			
			// calculate how high the box should be
			imgH = 295;//$(this).contents().filter("img").height();
			spanH = $(this).contents().filter(".span").height();
			newH = (fullH>(imgH+spanH)?fullH:(imgH+spanH));
			
			// get relevant vertical position info
			arrScroll = getScroll(); // array
			scrY = arrScroll[1]; // scrolled distance
			pTop = $("#grid").height() - ($(this).position().top + newH + 25); // does the box extend below the grid?
			oTop = $(window).height() - ($(this).offset().top + newH - scrY + 17); // does the box extend below the window?
			
			// tag as clicked, and disable hover events		
			$(this).addClass("clicked").unbind("mouseleave").unbind("mouseenter");
			
			// we're just centering the box. super custom
			$(this).animate({left: "63px"});
			$(this).animate({top: "25px"});
			
			/*
			// if the box extends out of the grid, move it back in
			if( ($(this).position().left+newW+25) > $("#grid").width() ) {
				$(this).animate({left: "+="+($("#grid").width() - ($(this).position().left+newW+55))+"px"});
				
			}*/
			
			// move box inside grid and/or window.
			//if( pTop < 0 || oTop < 0 ) $(this).animate({top: "+="+(pTop<oTop?pTop:oTop)+"px"});
			
			// animate box open
			$(this).queue(function() {
				$(this)
					.animate({width: newW+"px", padding: "5px", borderWidth:"3px",height: newH+"px"},250)
					.css({borderColor:'#666'});
				$(this).children().filter("img").animate({width: imgW+"px", height: imgH+"px"},250);
				$(this).dequeue();				
			})
			
			// put the z-index back a bit
			$(this).queue(function(){$(this).css("z-index",4);$(this).dequeue();});
			
		// need to collapse box
		} else if( $(this).width() >= exW ) {
			
			// stop any current animations
			$(this).stop();
			
			// empty queue
			$(this).queue([]);
			
			// movin' on down
			$(this).css("z-index",3);
			
			// activate hover events, remove clicked tag
			$(this).bind("mouseleave",boxUnhover).bind("mouseenter", boxHover).removeClass("clicked");
			
			// collapse box
			$(this)
				.animate({height: boxheight+"px",width: boxwidth+"px", padding: 0, borderWidth:"1px"},300)
				.css({borderColor:'#000'});
			$(this).children().filter("img").animate({width: "150px", height: "96px"},300);
				
			// force "unhover" event
			$(this).trigger("mouseleave");
			
			// put z-index back, and force grid sort
			$(this).queue(function(){$(this).css("z-index",0);grid(true,true);$(this).dequeue();});
			
		}
		
	});
	
	function getScroll() {
		
		var scrOfX = 0, scrOfY = 0;
		if( typeof( window.pageYOffset ) == 'number' ) {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		
		return [scrOfX, scrOfY]
	}
	

};


// starting the script on page load
$(document).ready(function(){
	
	// Don't do this in IE6; it is slooooooow.
	if(!(jQuery.browser.msie && (jQuery.browser.version.substr(0,1)=="6"))) load();
	
	// any images with the class 'hover' will add _ovr to the filename on hover
	// eg: test.jpg -> test_ovr.jpg
	$("img.hover").hover(function(e) {this.h = this.src;var tmp = this.h.split('/');var tmp2 = tmp[tmp.length-1].split('.');tmp2[0] += '_ovr';tmp2 = tmp2.join('.');tmp[tmp.length-1] = tmp2;var href = tmp.join('/');this.src = href;},function(){this.src = this.h;});
	
});