/*!
*	BRGDModal - Customized barebone reusable modal window
*
* 	Copyright (c) 2011 Ben Rhodes - bennrhodes(at)gmail(dot)com | http://www.benrhodesign.com
* 	Use freely for personal usage - Not for commercial use
* 	Date: 11/06/2011
* 	@author Ben Rhodes
* 	@version 0.1.0
*/
/* quick silly gif animation - replace with uid version to force refresh */
$('#identity').mouseover(function() {
  $('#identity').css('background-image', 'url(../img/'+stylecolor+'/logo_hover.gif'+ ')'); 
});

$('#identity').mouseout(function() {
  $('#identity').css('background-image', 'url(../img/'+stylecolor+'/logo.gif)'); 
});

var modalWindow
var fullscreenbg
var marginTop ;
var inScroll = false
var modalcarousel = null;
var currSlide = 1;
var windowLocation = new Number();
var pages = new Array();
var subnavedpages = new Array();
var entries = new Array();
var activeFilter = '#all';
var currHash = "";

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-23933128-1']);
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

function animatefullscreen_bgOn(){
	fullscreenbg.css({visibility: 'visible', opacity: '0'})
	fullscreenbg.animate( { opacity: '1', height: $(document).height(), top: '0'}, 200, function(){})
};
function animatefullscreen_bgOff(){
	fullscreenbg.animate( {opacity: '0', height:'0'}, 200, function(){ fullscreenbg.css({visibility: 'hidden', opacity: '0'}) })
};
function closePortfolio() {
	modalWindow.animate({ height: '1', top: modalWindow.height() / 2 + 227}, 400, function(){modalWindow.css({visibility:'hidden'})})
};
function updateImgNumber() {
	$('.portfolioitem').each(function(){
		$(this).find('.imgnumber').empty()
		var amnt = $(this).children('.portfolioitem_hiddenchild').length + 1
		$(this).find('.imgnumber').append('1 of ' + amnt)
		if (amnt == 1) {
			$(this).find('.viewmore').empty()
		}
	});
};
function openPortfolio(subject) {
	var xmlpath = subject.children(0).attr('rel').split(",")[0];
	entries = new Array();
	
	modalWindow.css({'height': '1'});
	
	var modtext = modalWindow.find('.wrap').find('.twocolumn')
	modtext.children().css({'opacity': '0'});
	modtext.children().each(function(index){
		$(this).delay(800 + (index*70)).animate({ opacity: '1'}, 400)
	})
	
	var modslider = modalWindow.find('.wrap').find('.sixcolumn')
	modslider.css({'opacity': '0'});
	modslider.delay(500).animate({ opacity: '1'}, 400)
	
	modalWindow.animate({ height: '455', top: modalWindow.height() / 2 + 227}, 400, function(){modalWindow.css({visibility:'visible'})})
	
	$.ajax({
		type: "GET",
		url: xmlpath,
		dataType: "xml",
		success: function (xml) {
			updateModal(xml);
		},
		404: function () {
			console.log('ajax get xml :: 404 ::');
		},
		error: function (jqXHR, textStatus, errorThrown) {
			console.log('ajax get xml :: fail :: ' + textStatus);
		}
	});
}

//called from ajax success - parsed xml is used to update the modal window with new images for jcarousel and copy/details/title
var updateModal = function (xml) {
	//create an array of images
	var hrefstring = $(xml).find('screens').attr('href');

	$(xml).find('screens').find('item').each(function () {
		var path = new String();
		path = $(this).text();
		var altstring = $(this).attr('alt');
		var obj = new Object({ src: path, dom: '<li><img src="' + path + '" width="643" height="374" alt="' + altstring + '" /></li>', href: hrefstring });
		
		entries.push(obj);
	});
	$('#portfolio_item_title').empty();
	$('#portfolio_item_copy').empty();
	$('#portfolio_item_title').append('<h4>'+$(xml).find('title').text()+'</h4>');
	$('#portfolio_item_copy').append($(xml).find('bodyhtml').text());
	if( hrefstring != '' ) {
		$('#portfolio_item_link').show();
		$('#portfolio_item_link a').attr('href', hrefstring)
	} else {
		$('#portfolio_item_link').hide();	
	}
		
	modalWindow.css({visibility:'visible'});
	
	//clear carousel and add new images
	addSlider();
	modalcarousel.reset();
	
	currSlide = 1;
	
	$.each(entries, function (index, value) {
		modalcarousel.add(index, entries[index].dom);
	});
	
	//udpate naviagtion
	checkActives();
}

function addSlider() {
	$('#modalslider').jcarousel({
		wrap: 'circular',
		scroll: 1,
		initCallback: modalcarousel_initCallback,
		buttonNextHTML: null,
		buttonPrevHTML: null,
		itemFirstOutCallback: {
			onBeforeAnimation: checkActives,
			onAfterAnimation: checkActives
		},
		itemVisibleInCallback: {
			onAfterAnimation: updateCollectionNumber
		}

	});

	$('#mycarousel-next').bind('click', function () {
		
		var active = getCurrentCarouselItem();
		var activesrc = $(active).children().last().attr('src');
		
		if (activesrc.trim() == String(entries[entries.length-1].src).trim() ) {
			return false;
		}
	
		modalcarousel.next();
		return false;
	});

	$('#mycarousel-prev').bind('click', function () {
		var active = getCurrentCarouselItem();
		var activesrc = $(active).children().first().attr('src');
		
		if (activesrc.trim() == String(entries[0].src).trim() ) {
			return false;
		}

		modalcarousel.prev();
		return false;
	});

	for (var i in document.links) {
		document.links[i].onfocus = document.links[i].blur;
		document.links[i].hideFocus = true;       // internet explorer
	}
}

function getCurrentCarouselItem() {
	var currSlide = null;
	
	$("#modalslider li").each(function () { 
		if ($(this).offset().left - 434 >= 0) {
			
			currSlide = $(this);
			return false;
		}
	});
	
	return currSlide;
}


function updateCollectionNumber(carouselitem, listobj, index, state) {
	
	$('#scr').empty();
	$('#scr').append(index + '/' + entries.length);
	
	/*
	if (entries[index - 1].href == undefined) {
		$('#launchsite').css('visibility', 'hidden');
		$('#collection').css('right', '0px');
	} else {
		$('#collection').css('right', '158px');
		$('#launchsite').css('visibility', 'visible');
		$('#launchsite').find('a').attr('href', entries[index - 1].href);
	}
	*/
}

//called when modal is opened, and when next/previous is clicked
//used to determine if any should change view to disabled
function checkActives() {
	var active = getCurrentCarouselItem();

	var firstactivesrc = $(active).children().first().attr('src');
	var lastactivesrc = $(active).children().last().attr('src');
	
	if (firstactivesrc.trim() == String(entries[0].src).trim()) {
		$("#mycarousel-prev").addClass('deactive');
	} else {
		$("#mycarousel-prev").removeClass('deactive');
	}
	
	if (lastactivesrc.trim() == String(entries[entries.length-1].src).trim()) {
		$("#mycarousel-next").addClass('deactive');
	} else {
		$("#mycarousel-next").removeClass('deactive');
	};
};

function lockDownPage() {
      var scrollPosition = [
        self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
        self.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
      ];
      var html = jQuery('html'); // it would make more sense to apply this to body, but IE7 won't have that
      html.data('scroll-position', scrollPosition);
      html.data('previous-overflow', html.css('overflow'));
      html.css({'overflow': 'hidden'});
	  
      window.scrollTo(scrollPosition[0], scrollPosition[1]);
}

function releasePage() {
      var html = jQuery('html');
      var scrollPosition = html.data('scroll-position');
	  
      html.css('overflow', html.data('previous-overflow'));
      window.scrollTo(scrollPosition[0], scrollPosition[1]);
	  
}

function modalcarousel_initCallback(carousel) {
	modalcarousel = carousel;
};

function addPortfolioItems() {
	if( $('#portfolio').length ) {
		$.ajax({
			type: "GET",
			url: 'portfolio/projects.xml',
			dataType: "xml",
			success: function (xml) {
				//for each item in projects.xml append html with markup
				var portfoliocontainer = $('#portfolio');
				$(xml).find('item').each(function () {
					var project_item = '<div class="' +  $(this).attr('cssclass') + '">'
					+ '<a href="#" rel="' + $(this).attr('xmlsrc') + ',#all,' + $(this).attr('filters') +'">'
					+ '<img src="' + $(this).attr('thumbsrc') +'" width="223" height="167" alt="' + $(this).attr('thumbalt') + '"/>'
					+ '<div class="details">'
					+ $(this).find('details').text()
					+ $(this).find('cta').text()
					+ '</div>'
					+ '</a></div>';
					
					portfoliocontainer.append(project_item);
				});
				//update laters
				updateImgNumber();
				
				//each project has this click listener
				$('.project').click(function(){
					lockDownPage();
					openPortfolio($(this));
					animatefullscreen_bgOn();
				});
				
				//setup filters
				$('.filter').find('a').click(function(event){
					event.preventDefault();
					$('.filter').removeClass('on');
					$(this).parent().addClass('on');
					var activefilter = $(this).attr('href');
					$('.project').each(function() {
						var itemsfilters = new Array;
						itemsfilters = $(this).find('a').attr('rel').split(',');
						
						var pass = new Boolean;
						pass = false;
						for (var i = 0; i < itemsfilters.length; i++) {
							if( itemsfilters[i] == activefilter ) {
								pass=true;
							}
						}
						
						if(pass) {
							$(this).css({'visibility' : 'visible', 'display':'block'});
						} else {
							 $(this).css({'visibility' : 'hidden', 'display':'none'}); 
						}
					});
				});
				
			},
			404: function () {
				console.log('ajax get xml :: 404 ::');
			},
			error: function (jqXHR, textStatus, errorThrown) {
				console.log('ajax get xml :: fail :: ' + textStatus);
			}
		});
	}
}

$(document).ready( function(){
	modalWindow = $('#modal');
	fullscreenbg = $('#fsbg');
	
	addPortfolioItems()
	$('#fsbg').click(function(){
		releasePage();
		animatefullscreen_bgOff();
		closePortfolio();
	})
	$('#modal').children('.close').click(function(){ 
		releasePage();
		animatefullscreen_bgOff();
		closePortfolio();
	});
	
	$(".inputfo").click(function(e){
		$(this).attr('value', '');
	});
	
	$('.inputfo').blur(function() {
	  if( $(this).attr('value') == '' ) {
		  $(this).attr('value', $(this).attr('onBlur') );
	  }
	});
	
	marginTop = $('#folio').offset().top;
	SetUpNavDrops();
	SetUpScrollTo();
	
	// $(window).hashchange();
});















function SetUpNavDrops() {
	var nav = $("nav ul");
	nav.find("li").each(function() {
		if ($(this).find("ul").length > 0) {
			$(this).find("ul").stop(true, true).slideUp(0);
			//show
			$(this).mouseenter(function() {
				$(this).find("ul").stop(true, true).slideDown(250);
			});			
			//hide
			$(this).mouseleave(function() {
				$(this).find("ul").stop(true, true).slideUp(0);
			});
		}
	});
}

function SetUpScrollTo(){
	var mainnav = $('nav');
	/*
	$('.subnav').each(function(s){
		var id = $(this).attr('id')
		$(this).find('a').each(function(){
			$(this).bind('click', click);
			var subAttr = new Array();
			subAttr['href'] = $(this).attr('href')
			subAttr['id'] = id
			if( subAttr['href'].charAt(0) == '#' ) { subnavedpages.push(subAttr) }
		});
	});
	*/
		mainnav.find('li').each(function(){				 
		var link = $(this).children('a');
		if( link.attr('href').charAt(0) != '#' ) { return };
		
		link.bind('click', click);
		$('.footnav li a').each(function(){	

		 if( $(this).attr('target') != '_blank' ) {
			 $(this).bind('click', click);
		 }
		});
		
		var page = new Object();
		var pageid = link.attr('href');
		var fail = false;
		
		jQuery.each(pages, function(i) {
		  if( pageid == pages[i]['id'] ) { fail = true };
		});
		if(!fail && $(pageid).offset() != null) {
			var pageObj = $(pageid);
			page['id'] = pageid;
			page['top'] = pageObj.offset().top;
			page['bottom'] = page['top'] + pageObj.height();
			page['title'] = pageObj.attr('title');
			page['hasSub'] = false;;
			page['catagory'] = 'Pages';
			page['action'] = 'Animate to Page';
			page['label'] = pageid + ' Visited';
			page['navbutton'] = link.parent();
			/*
			jQuery.each(subnavedpages, function(s) {						
				if( subnavedpages[s]['href'] == pageid ) { page['hasSub'] = true; page['subId'] = subnavedpages[s]['id'] }
			});
			*/
			
			pages.push( page );
		}
	});
	$(window).scroll(onScroll);
	onScroll();
};

var onScroll = function(e){
	var vistaTop = getScrollTop() + marginTop;
    var vistaBottom = vistaTop + document.body.offsetHeight;
	var vista = new Array();
	jQuery.each(pages, function(i) {
		//alert(pages[i]['bottom'] +'    '+ vistaTop + '    ' +pages[i]['top'] + '   ' +vistaBottom)
		var invista = ((pages[i]['bottom'] >= vistaTop) && (pages[i]['top'] <= vistaBottom));
		
		if(invista) { vista.push(i); };
	});
	
	activePage(vista[0]);
	//document.title = '#' + window.location.hash.split('/')[1] + '-subnav'
	/*
	$('aside').each(function(){
		if( $(this).attr('id') == '#' + window.location.hash.split('/')[1] + '-subnav' ) {
		 	var subinuse = $(this);
			var pindex = vista[0];
			var navOffsetAmt =  $(pages[pindex]['id']).offset().top + getScrollTop() - marginTop
			//navOffsetAmt = getScrollTop() - $(pages[pindex]['id']).height();
			subinuse.stop().animate({'top':navOffsetAmt}, 200);
			document.title = 'page' + $(pages[pindex]['id']).offset().top + '  scroll' + getScrollTop()
			
		}
	});*/
		if( $('#' + window.location.hash.split('/')[1] + '-subnav' ).length > 0 ) {
			
			//var subinuse = $('#' + window.location.hash.split('/')[1] + 'subnav')
			var pindex = vista[0];
			var navOffsetAmt =  pages[pindex]['top'];
			//document.title = pages[pindex]['id']
			navOffsetAmt = getScrollTop() - $(pages[pindex]['id']).height();
			/*
			if ( navOffsetAmt + 40 > pages[pindex]['bottom'] - subinuse.height() + 88 ) { 
				navOffsetAmt = pages[pindex]['bottom'] - subinuse.height() + 88;
			}
			if ( navOffsetAmt - 20 < pages[pindex]['top'] ) { 
				navOffsetAmt = pages[pindex]['top'];
			}*/
			
			subinuse.css({'top':navOffsetAmt});
			//document.title = navOffsetAmt;
		}
	
};

var click = function(e){
	
	var pageidname = this.href.split("#")[1];
	currHash = '/'+pageidname;
	window.location.hash = currHash;
	e.preventDefault();
	
	gotoPage(pageidname);
};

function gotoPage(hashid){
	//alert(hashid)
	var hbod = $('html,body');
	var from = getScrollTop();
	hbod.stop();
	
	setNavActiveState();
	
	var cObj = $('#'+hashid);
	
	var marginAmt = marginTop;
	if( hashid = 'mathrandom' ) { marginAmt = 140;}; 
    var goingTo = cObj.offset().top - marginAmt;
	var distance = goingTo - from;
	
	var inc = goingTo > from ? goingTo - from : from - goingTo;
	inScroll = true;
	var once = 0;
	
	hbod.animate({scrollTop:goingTo}, 1000 * inc/1300, 'easeInOutQuad', function(){ 
		once++; 
		if( once== 1) {
			inScroll = false; 
			activePage(0);
		}
	});
	_gaq.push(['_trackEvent', 'Page View', 'from main navigation', hashid]);
}

function setNavActiveState() {
	$('nav li a').each(function(){
		var ihash = '#/'+$(this).attr( 'href' ).split('#')[1];
		
		ihash === location.hash ? $(this).parent().addClass('on') : $(this).parent().removeClass('on');
		
	});
	
	if(location.hash == '#/skills' || location.hash == '#/pointofdifference' || location.hash == '#/info'){
		location.hash = '#/aboutben/' + location.hash.substring(2, location.hash.length);
		$('nav li a[href="#aboutben"]').first().parent().addClass('on'); 
	}
}

var activePage = function(pindex) {
	if( currHash !=  '/'+pages[pindex]['id'] && !inScroll) {
	currHash = '/'+pages[pindex]['id'];

	window.location.hash = '/'+pages[pindex]['id'].split('#')[1];
	if(!inScroll) {
		setNavActiveState();
	}
	
	document.title = 'benrhodesign | ' + pages[pindex]['title'];
	_gaq.push(['_trackEvent', 'Page View', 'from scrolling', pages[pindex]['id']]);
	
	customByPageIdAnimation(pages[pindex]['id']);
	
	
	/*
	//check for subnav
	if( pages[pindex]['hasSub'] == true ) { 
		var subinuse = $('#'+pages[pindex]['subId'])
		subinuse.css({'visibility': 'visible'})
		var navOffsetAmt =  pages[pindex]['top']
		navOffsetAmt = getScrollTop() + marginTop
		if ( navOffsetAmt + 40 > pages[pindex]['bottom'] - subinuse.height() + 88 ) { navOffsetAmt = pages[pindex]['bottom'] - subinuse.height() + 88}
		if ( navOffsetAmt - 20 < pages[pindex]['top'] ) { navOffsetAmt = pages[pindex]['top'] }
		subinuse.css({'top':navOffsetAmt, 'left':$('.wrapperplusmargin').first().offset().left });
		subinuse.find('a').each(function(){
			if($(this).hasClass('on')) { $(this).removeClass('on') }
			if($(this).attr('href') == pages[pindex]['id'] ){ $(this).addClass('on')};								
		});
	} else {
		$('.subnav').each(function(){ $(this).css({'visibility': 'hidden'})});
	}
	*/
	}
}

function customByPageIdAnimation(id){
	resetAll();
	
	switch(id)
	{
	case '#skills':
	
	  $('.scale').show();
	  $(id).find('.scale').each(function(index) {
		  $(this).width(0);
		  
		  $(this).delay(500).animate({
			width: $(this).attr('data-width')
		  }, 2000 );
	  });
	break;
	case '#pointofdifference':
	  
	break;
	case '#contact':
	break;
	case '#aboutben':
	$(id).find('img').each(function() {
		$(this).fadeOut(0);
		$(this).fadeIn(1000);
	});
	break;
	case '#folio':
	//$(this 'img').child('img').delay(300).fadeIn(1000);
	break;
	default:
	break;
	}
}

function resetAll(){
	
	$('.scale').hide();
	
}

$(window).hashchange( function(){
	//alert(location.hash.split('/')[1])
	//gotoPage(location.hash.split('/')[1])
	
});

var getScrollTop = function(){
    if(document.documentElement.scrollTop <= document.body.scrollTop) return document.body.scrollTop;
    if(document.documentElement.scrollTop > document.body.scrollTop) return document.documentElement.scrollTop;
    return 0;
};

jQuery.extend( jQuery.easing,
{
	easeInOutQuad: function (nulld, time, from, to, duration) {
		if ((time/=duration/2) < 1) return to/2*time*time + from;
		return -to/2 * ((--time)*(time-2) - 1) + from;
	}
});
