// JavaScript Document

var activesection = '';
var activesort = '';
var workpositions = [];
var currentimage;

function fontready() {
	$('h1.active .bg').animate({'width':$('h1.active').find('.txt').width() + 40}, 0);
}

// SHOW THE SECTIONS ON THE HOMEPAGE
function showcontent(_id) {
	
	if(_gaq) _gaq.push(['_trackPageview', '/'+_id]);
		
	if($('h1.active').length == 0) $('#'+_id+'_btn').mouseenter().addClass('active');
	
	$('.homecontent.active').slideUp(300).removeClass('active');
	
	// CLOSING CURRENTLY OPEN SECTION WHEN CLICKED ON AGAIN 
	if(activesection == _id) {
		activesection = '';
		$('#'+_id+'_btn').removeClass('active'); // FIX THE NAV WHEN THIS HAPPENS
		return;
	} else $('#'+_id+'_btn').mouseenter(); // FIX ClICK TO CLOSE THEN OPEN AGAIN AND NOT ROLL OUT
	
	$('#'+_id).slideDown(300).addClass('active');	
	if(isiPhone()) {
		var over = jQuery.proxy(navover, $('h1.active'));
		over(); 	
	}
	
	//if(_id == 'work' && $.Storage.get('sorted')) $('#'+$.Storage.get('sorted')+'-sort').click();
	
	activesection = _id;	
		
}

function namesort(a, b){
	var nameA=$(a).find('a').html().toLowerCase(), nameB=$(b).find('a').html().toLowerCase();
	if (nameA < nameB) //sort string ascending
		return -1; 
	if (nameA > nameB)
		return 1;
	return 0; //default return value (no sorting)
}

function datesort(a, b) {
  // This is a comparison function that will result in dates being sorted in
  // DESCENDING order.
	var d1 = $(a).attr('data').toString().split('/');
	var d2 = $(b).attr('data').toString().split('/');
	var date1 = new Date(d1[2], d1[0], d1[1]);
	var date2 = new Date(d2[2], d2[0], d2[1]);
	if (date1 > date2) return -1;
	if (date1 < date2) return 1;
	
	return namesort(a, b); // IF DATES THE SAME SORT BY NAME
	
	return 0;
};


function sortby(_sort) {
	
	if(_sort == '') return;
	
	if(workpositions.length == 0) {
		$('#worklisting li').each(
			function() {
				workpositions.push($(this).position()['top']);
			}
		)
		$('#worklisting').css('height', $('#worklisting').height()); //.length * $('#worklisting li:first-child').css('height')); 
	}
	
	var sorted = [];
	var rest = [];
	var domorder = [];
	var c = 0;
	var s = 0;
	
	if(_sort == 'date') { 
		
		$('#worklisting li').each(
			function() { 
				//$(this).removeClass('unsorted');
				//$(this).find('a').css('color', null);
				$(this).find('a').animate({'color':'#5B4F46'}, 500);
				rest.push($(this));
				
				$(this).css({'position':'absolute', 'top':workpositions[c]+'px'});		
				c++;
			}
		).find('.thedate').animate({'opacity':1}, 500);
		rest.sort(datesort);
		
		
	} else {
				
		$('#worklisting li').each(
			function() {
								
				if($(this).hasClass(_sort) || _sort == 'name') { 
					//$(this).removeClass('unsorted');
					$(this).find('a').animate({'color':'#5B4F46'}, 500);
					sorted.push($(this));	
				} else {
					rest.push($(this)); 
					//$(this).addClass('unsorted');
					$(this).find('a').animate({'color':'#828282'}, 500);
				}
				
				$(this).css({'position':'absolute', 'top':workpositions[c]+'px'});
				//$(this).animate({'top':workpositions[c]+'px'}, 700, 'easeOutQuint');		
				c++;
			}
		).find('.thedate').animate({'opacity':0}, 500);
		
		sorted.sort(namesort);
		rest.sort(namesort);
		
		for(var s = 0; s < sorted.length; s++) {
			domorder[workpositions[s]] = $(sorted[s]);
			$(sorted[s]).animate({'top':workpositions[s]+'px'}, 700, 'easeOutQuint');	
		}
	}
		
	for(var r = 0; r < rest.length; r++) {
		domorder[workpositions[s+r]] = $(rest[r]);
		$(rest[r]).animate({'top':workpositions[s + r]+'px'}, 700, 'easeOutQuint');	
	}
	
	// REORDER THE DOM FOR THE NEXT SORT
	for(var p = 0; p<workpositions.length; p++) {
		var li = $(domorder[workpositions[p]]).detach()
		li.appendTo('#worklisting');
	}
	
	activesort = _sort;
}

function sortclick() {
	if($(this).hasClass('active')) return;
	
	if(_gaq) _gaq.push(['_trackEvent', $(this).attr('id'), 'clicked']);
	
	$('#worksorting .active').removeClass('active');
	
	sortby($(this).html());
	
	$(this).addClass('active');
}

function imagenumberclick(event) {
	event.preventDefault();
	var num = $(this).attr('href');
	
	changeimage(num);	
}

function imagearrowclick(event) {
	event.preventDefault();
	
	if($(this).hasClass('inactive')) return;
	
	var dir = $(this).attr('id') == 'leftbtn' ? -1 : 1;
	var nextimage = dir + currentimage; 
	
	changeimage(nextimage);
}

function changeimage(nextimage) { 
	
	if(nextimage >= totalimages) nextimage = totalimages - 1;
	else if(nextimage < 0) nextimage = 0;	
	
	currentimage = parseInt(nextimage);
	
	$('#works').animate({left:-$('#works li:eq('+currentimage+')').position().left  }, 400);
	
	$('#caption').html($('#works li:eq('+currentimage+') img').attr('title'));
	
	if(currentimage > 0) $('#leftbtn').removeClass('inactive');
	else $('#leftbtn').addClass('inactive').mouseout();
	
	if(currentimage >= totalimages - 1) $('#rightbtn').addClass('inactive').mouseout();
	else $('#rightbtn').removeClass('inactive');
	
	$('#imagecount a.active').removeClass('active');
	$('#imagecount a[href="'+currentimage+'"]').addClass('active');
	
	$('#worksholder').animate({'height':$('#works li:eq('+currentimage+') img').height()}, 600)
	
}

$(function() {
		
// ADD THE FUNCTIONALITY TO THE HOMEPAGE MENU ITEMS	
	$('h1').click(function() {
				
		if(_gaq) _gaq.push(['_trackEvent', $(this).attr('id'), 'clicked']);
		
		var out = jQuery.proxy(navout, $('h1.active'));
		
		$('h1.active').removeClass('active').mouseleave();
		if(isiPhone()) out();
		
		$(this).addClass('active');
		
		var id = $(this).attr('id');
		var sectionid = id.substring(0, id.indexOf('_'));
		showcontent(sectionid);
		
	});
	
	if(!isiPhone()) { // ONLY ADD ROLLOVER TO NON TOUCH DEVICES
		$('h1').hover(navover, navout);
	}
	
	$('.workbtn').hover(
		function() {
			if($(this).hasClass('inactive')) return;
			var id = $(this).attr('id');
			var side = id.substring(0, id.indexOf('btn'));
			$('#'+side+'arrow').animate({'opacity':1}, 600);
		}, 
		function() {
			var id = $(this).attr('id');
			var side = id.substring(0, id.indexOf('btn'));
			$('#'+side+'arrow').animate({'opacity':0}, 600);
		}
	).click(imagearrowclick);
	/*
	$('#works li:eq(0) img').load(function(){
		//$('#worksholder').animate({'height':$('#works li:eq(0) img').height()}, 600);
		//$('#worksholder').css({'height':$(this).height()});
	}).each(function(){
		if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6)) 
			$(this).trigger("load");
	});
	//.load(function() { console.log($('#works li:eq(0) img').height()); $('#worksholder').animate({'height':$('#works li:eq(0) img').height()}, 600); } );
	*/
	
	currentimage = 0;
	totalimages = $('#works li').length;
	
	$('#leftbtn').addClass('inactive');
	if(totalimages <= 1) $('#rightbtn').addClass('inactive');
	$('#imagecount a[href="'+currentimage+'"]').addClass('active');
	$('#imagecount a').click(imagenumberclick);
	
	$('#worksorting a').click(sortclick);
	$('#worklisting li a').click(function() { $.Storage.set({"viewing":activesection, "sorted":activesort}); });
	
	$('#logo').click(function() { $.Storage.remove('viewing'); $.Storage.remove('sorted'); });
	
	$('#name-sort').addClass('active');
	
	//if($.Storage.get("viewing")) showcontent($.Storage.get('viewing'));
	//if(!$.Storage.get("sorted")) { $('#name-sort').addClass('active'); }
});

function navover() { 
	$(this).animate({'color':'#FFF'}, 400).find('.bg').animate({'width':$(this).find('.txt').width() + 40}, 400); 
	$(this).find('.icon').delay(200).animate({'opacity':1}, 400);
}

function navout() { 
	//$(this).removeClass('over'); 
	if(!$(this).hasClass('active')) {
		$(this).animate({'color':'#5B4F46'}, 400).find('.bg').animate({'width':0}, 400); 
		$(this).find('.icon').animate({'opacity':0}, 100);
	}
}

function isiPhone(){
    return (
        (navigator.platform.toLowerCase().indexOf("iphone") != -1) ||
        (navigator.platform.toLowerCase().indexOf("ipod") != -1) || 
		(navigator.platform.toLowerCase().indexOf("ipad") != -1) ||
		(navigator.platform.toLowerCase().indexOf("android") != -1)
    );
}
