google.load("gdata", "2.x", {packages: ["blogger"]});

//ipad/iphone switch
var ua = navigator.userAgent;
var checker_all = ua.match(/(iPhone|iPod|iPad|BlackBerry|Android)/);
var checker = {
  iphone: ua.match(/(iPhone|iPod|iPad)/),
  blackberry: ua.match(/BlackBerry/),
  android: ua.match(/Android/)
};

$(function() {

	//pages loaded
	var boo_home_loaded = false;
	var boo_commissioned_loaded = false;
	var boo_commissioned_album_loaded = false;
	var boo_news_loaded = false;
	var boo_personal_loaded = false;
	var boo_personal_album_loaded = false;
	var boo_news_entry_loaded = false;
	var boo_all_loaded = false;
	var boo_info_loaded = false;
	var boo_overview_loaded = false;
	var boo_slider_loaded = false;
	var boo_all_albums_loaded = false;
	
	var boo_mobile_touch_nav = false;
	var boo_all_photos_loaded = false;
	var boo_gallery_animated_in = false;
	var current_overview_id = null;
	var picasa_feed = 'http://picasaweb.google.com/data/feed/api/user/joshcole.co.uk';
	var blog_feed = 'http://joshcolesworld.blogspot.com/feeds/posts/default';
	var arr_hash = new Array();
	var full_page = null;
	var full_new_page = window.location.hash;
	var page = process_hash(window.location.hash);
	var new_page = null;
	var nav_speed = 10;
	var gallery_columns = {};
	var boo_gallery = false;
	var arr_cur_gallery = new Array();
	var cur_gallery_type = null;
	var all_photos = new Array();
	var personal_albums = new Array();
	var commissioned_albums = new Array();
	var albums_object = {};
	var all_photos_object = {};
	var boo_resized = false;
	var blogger_service;
	var cur_pagination_index = 1;
	var cur_blog_index = 1;
	var arr_blog_entries = new Array();
	var arr_info = new Array();
	var total_blog_entries = 0;
	var str_news_html = '';
	var scroll_active;
	var gallery_build_count = 0;
	var gallery_scroll_active = {};
	var slider_moved = false;
	var m_names = new Array("January", "February", "March", 
			"April", "May", "June", "July", "August", "September", 
			"October", "November", "December");
	var settings = {
       		'buffer': 50,
       		'fireOnDocEnd': true,
       		'fireOnBeyondElement' : true
       	};
	var twitter = $('<a/>').addClass('twitter')
							.attr('href','https://twitter.com/share?url=')
							.attr('target','_blank')
							.attr('title',"Share Josh Cole's work on Twitter")
							.append($('<img/>').attr('src','css/images/twitter.png'))
							.after('<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>');
	var facebook = $('<a/>').addClass('facebook')
							.attr('target','_blank')
							.append($('<img/>').attr('src','css/images/facebook.png'));
	var share = $('<p><span class="share_text">Share.</span><br/></p>').addClass('share').append(twitter).append(facebook);
	
	
	
	if(checker.iphone || checker.ipad)
	{
		$('nav, .slider_info_wrapper h2, .entry_wrapper h2').css('font-size','1.6em');
		if ( window.orientation == 0 || window.orientation == 180 ) {
			//portrait
			$('nav').css('line-height','1.4em');
		}
		else
		{
			$('nav').css('line-height','2em');
		}
		window.onorientationchange = function(){
			if ( window.orientation == 0 || window.orientation == 180 ) {
				//portrait
				$('nav').css('line-height','1.4em');
			}
			else
			{
				$('nav').css('line-height','2em');
			}
		};
	}
	
	var mouseenterevent = checker_all ? "touchstart" : "mouseenter";
    var clickevent = checker_all ? "touchstart" : "click";

	
	//get the url and redirect if necessary
	if(window.location.pathname != '/' && window.location.pathname != '/studio_output/')
	{
		var path = window.location.pathname;
		location.href = 'http://' +window.location.hostname  + '#' + path.substring(1);
	}
	
	
	$(window).hashchange( function(){
		if(boo_all_photos_loaded)
		{
			//prevent from going dead
			$.logThis('change page hash change: ' + full_page);
			if(window.location.hash != full_page)
			{
				change_page();
			}
		}
	});
	
	init_nav();
	preload();
	
	
	$("#wrapper").bind('show_page_in',function(e){ $.logThis('trigger show_page line 18'); show_page('in');});

	//do stuff for news
	google.setOnLoadCallback(function(){
		$.logThis('blog service loaded');
		blogger_service = new google.gdata.blogger.BloggerService('GoogleInc-jsguide-1.0');
		blogger_service.getBlogFeed(blog_feed+ '?max-results=9&start-index=1',handle_blog_feed,handle_blog_error);
		cur_blog_index = 10;
	});
	
	function handle_blog_error(error) {
		  $.logThis(error);
	}
	function handle_blog_feed(blogFeedRoot) {
		
		total_blog_entries = blogFeedRoot.feed.getTotalResults().$t;
		arr_blog_entries = blogFeedRoot.feed.getEntries();
		if(!arr_blog_entries.length){
			$.logThis("blog feed loaded - no entries");
	    	return;
		}
		else 
		{
			if(window.location.hash.search('#news') == 0)
			{
				load_albums();
				$.logThis('blog feed loaded, lets rock!');
				$("#wrapper").trigger('show_page_in');
			}
		}
	}

	function process_hash(raw_hash)
	{
		if(!raw_hash)
		{
			$.logThis('process_hash - no hash!');
			return ;
		}
		arr_hash = raw_hash.replace('#', '').split('-');
		return arr_hash[0];
	}
	
	function init_nav() {
		
		// show only on mouseover
		//$('.nav_item').css('opacity',0);
		
		$('.nav_item').hide();
		
		if(checker_all)
		{
			$('.nav_home a').bind('touchstart',function(e){
				e.preventDefault();
				if(boo_mobile_touch_nav)
				{
					$.logThis('GO TO HOMEPAGE');
					boo_mobile_touch_nav = false;
					change_page(this.hash);
				}
				else
				{
					$.logThis('FADE NAV IN');
					boo_mobile_touch_nav = true;
					$('.nav_bg').stop().fadeTo('fast',1);
					$('.nav_item').stop().fadeTo('fast',1);
					$('.nav_home').stop().fadeTo('fast',1);
					$('#nav_wrapper').css('overflow','visible');
				}
			});
			$('.nav_home a').bind('touchend',function(e){$.logThis('FIRE END');});
			$('.nav_home a').mouseenter(function(e){$.logThis('FIRE mouseenter');});
			
			$('.nav_item a').click(function(event) {
				event.preventDefault();
				change_page(this.hash);
				fade_out_nav();
			});
			
			$('.nav_item, .sub_nav_item').bind('touchstart',function(){$(this).children('a:not(".active")').css('border-bottom','2px solid');});
			$('.nav_item, .sub_nav_item').bind('touchend',function(){$(this).children('a:not(".active")').css('border-bottom','none');});
			
			$('#slider_wrapper').live('touchstart',function(){fade_out_nav();});
			$('#content').live('touchstart',function(){fade_out_nav();});
		}
		else
		{
			$('.nav_home').bind(mouseenterevent,function(){
				$('.nav_bg').stop().fadeTo('fast',1);
				$('.nav_item').stop().fadeTo('fast',1);
				$('.nav_home').stop().fadeTo('fast',1);
				$('#nav_wrapper').css('overflow','visible');
			});
			
			$('#nav_wrapper').hover(function(){
				//$('.nav_home').fadeTo(400,1);
				$('.nav_bg').stop().fadeTo('fast',1);
				$('.nav_item').stop().fadeTo('fast',1);
				$('.nav_home').stop().fadeTo('fast',1);
				$(this).css('overflow','visible');
			},function(){
				fade_out_nav();
			});
			
			$('.nav_item, .sub_nav_item').live({
		        mouseenter:
		            function()
		            {
		        	$(this).children('a:not(".active")').css('border-bottom','2px solid');
		            },
		         mouseleave:
		            function()
		            {
		        	 $(this).children('a:not(".active")').css('border-bottom','none');
		            }
		        });
			//do onclick
			$('.nav_item a,.nav_home a').click(function(event) {
				event.preventDefault();
				change_page(this.hash);
			});
		}
		
				
		
		
		/*$(window).scroll(function () {  
			var offset = $(document).scrollTop();
			$('#nav_wrapper').animate({top:offset},{duration:300,queue:false,complete:function(){}});  
			$('.nav_bg').animate({top:offset},{duration:300,queue:false,complete:function(){}});  
	    }); 
	    */ 
	}
	
	function fade_out_nav() {
		//$('.nav_bg').css('top',$('#nav_wrapper').css('top'));  
		$('.nav_bg').stop().fadeTo('fast',0);
		$('.nav_item').stop().fadeTo('fast',0);
		$('#nav_wrapper').css('overflow','hidden');
		boo_mobile_touch_nav = false;
	}
	
	var t;
	function change_page(my_hash)
	{
		clearTimeout(t);
		t = setTimeout(function(){
			if(!my_hash)
			{
				my_hash = window.location.hash;
			}
			full_new_page = my_hash;
			$.logThis('change_page from: ' + full_page+' to:' + full_new_page);
			if(full_page != full_new_page)
			{
				window.location.hash = my_hash;
				new_page = process_hash(my_hash);
				if(full_page)
				{
					$.logThis('change_page 1');
					fade_out_nav();
					show_page('out');
				}
				else
				{
					$.logThis('change_page 2');
					show_page('out');
					/*
					//initiate in
					if(boo_home_loaded)
					{
						$.logThis('change_page 3');
						show_page('out');
					}
					else
					{
						$.logThis('change_page 4');
						$("#wrapper").trigger('show_page_in');
					}*/
					
				}
				full_page = full_new_page;
			}
			else
			{
				$.logThis('Where should I go? ' + full_page + ' ' + full_new_page);
			}
		},700);
	}
	
	function checkUrl(url) {
		
	}

	var boo_slider_preloaded = false;
	function load_single_album(album_id)
	{
		$.logThis('load_single_album');
		var album_feed = picasa_feed + '/albumid/'+album_id+'?alt=json&kind=photo';
		$.ajax({
			dataType : "jsonp",
			error : function() {
				$.logThis('error load_single_album '+album_feed+' ');
			},
			cache : false,
			url : album_feed,
			success : function(data) {
				if(!boo_slider_preloaded && !boo_slider_loaded)
				{
					boo_slider_loaded = true;
					boo_slider_preloaded = true;
					var album = format_album(data.feed);
					albums_object[album_id] = album;
					var album_count = 0;
					album.photos = new Array();
					$.each(album.entry, function(i, item) {
						if(item.summary.$t != 'thumb')
						{
							album_count++;
							item.position = album_count.toString();
						}
					});
					$.each(album.entry,function(i,item){
						if(item.summary.$t != 'thumb')
						{
							item = format_photo(item,album,album_count);
							all_photos_object[item.gphoto$id.$t] = item;
							album.photos.push(item);
						}
					});
					
					$('#wrapper').height('');
					$.logThis('load_single_album - preload slider');
					build_album(arr_hash[1],'slider');
					load_albums();
				}
			}
		});
	}
	
	/* Load all data from google picasa account */
	function preload() {
		
		//show loading bar
		var screen_height = (checker.iphone || checker.ipad) ? window.innerHeight : $(window).height();
		$('#wrapper').height(screen_height - $('#nav').height()).css('background','url("css/images/loader.gif") no-repeat center center');

		
		
		//preload homepage faster
		if(!window.location.hash || window.location.hash == '#home')
		{
			build_home();
			if(!full_page)
			{
				//full_page = window.location.hash;
			}
			load_albums();
		}
		else if(window.location.hash.search('#slider') == 0)
		{
			//preload slider faster
			var album_id = arr_hash[1];
			
			if(albums_object[album_id] == undefined)
			{
				//try an image
				var image_feed = picasa_feed + '/photoid/'+arr_hash[1]+'?alt=json';
				$.ajax({
					dataType : "jsonp",
					error : function() {
						$.logThis('error preload slider image feed '+ image_feed + ' ' + thrownError);
					},
					cache : false,
					url : image_feed,
					success : function(data) {
						$.logThis('preload single album ');
			        	load_single_album(data.feed.gphoto$albumid.$t);
					}
				});
				
				//try for an album
				load_single_album(arr_hash[1]);
			}
		}
		else if(window.location.hash.search('#news') == 0)
		{
			
		}
		else
		{
			load_albums();
		}

		//info album
		var info_feed = picasa_feed + '/album/info?alt=json&kind=photo';
		$.ajax({
					dataType : "jsonp",
					error : function() {
						$.logThis('error - info album could not load');
					},
					cache : false,
					url : info_feed,
					success : function(data) {
						arr_info = data.feed.entry;
						//load info page faster
						if(window.location.hash == '#info' && !boo_info_loaded)
						{
							$('#wrapper').height('');
							$.logThis('show info page faster');
							show_page('in');
						}
					}
				});
	}
	
	function load_albums()
	{
		$.logThis('load_albums');
		//albums
		var album_feed = picasa_feed + '?alt=json&kind=album&hl=en_GB&callback=?&';
		$.ajax({
			dataType : "jsonp",
			error : function() {
				$.logThis('error - albums could not load!');
			},
			cache : false,
			url : album_feed,
			success : function(data) {
				
				process_loaded_album(data);
			}
		});
	}
	
	function format_album(album)
	{
		var arr_tmp_title = album.title.$t.split(' ');
		var arr_tmp_order = arr_tmp_title[0].split('-');
		if(arr_tmp_order[1])
		{
			album.order_by = parseInt(arr_tmp_order[1],10);
		}
		delete arr_tmp_title[0];
		if(album.title.$t.indexOf("pp-") == 0 || album.title.$t.indexOf("cp-") == 0)
		{
			album.type = 'Photography';
		}
		else
		{
			album.type = 'Film';
		}
		album.clean_title = jQuery.trim(arr_tmp_title.join(' '));
		if(album.title.$t.indexOf("pp-") == 0 || album.title.$t.indexOf("pv-") == 0)
		{
			album.clean_section = 'Personal';
			album.clean_section_url = 'personal';
		}
		else
		{
			album.clean_section = 'Commissioned';
			album.clean_section_url = 'commissioned';
		}
		album.info = album.type+'.<br/>';
		var album_date = new Date(parseInt(album.gphoto$timestamp.$t));
		album.info += album_date.getFullYear()+'<br/>';
		album.info += album.type == 'Photography' ? 'Images.<br/>' : 'Videos.<br/>';
		return album;
	}
	
	function process_loaded_album(data)
	{
		var count = 0;
		$.each(data.feed.entry, function(i, item) {
			if(item.title.$t.indexOf("pp-") == 0 || item.title.$t.indexOf("pv-") == 0 || item.title.$t.indexOf("cp-") == 0 || item.title.$t.indexOf("cv-") == 0)
			{
				item = format_album(item);
				count++;
			}
		});
		$.each(data.feed.entry, function(i, item) {
			if(item.title.$t.indexOf("pp-") == 0 || item.title.$t.indexOf("pv-") == 0)
			{
				get_album_photos(item,personal_albums,count);
			}
			
			if(item.title.$t.indexOf("cp-") == 0 || item.title.$t.indexOf("cv-") == 0)
			{
				get_album_photos(item,commissioned_albums,count);
			}
			
		});
	}
	
	function format_photo(item,album,album_count)
	{
		item.clean_title = item.summary.$t ? item.summary.$t : album.clean_title;
		item.clean_section = album.clean_section;
		item.clean_section_url = album.clean_section_url;
		item.info = album.type == 'Photography' ? 'Image.' : 'Video.';
		item.info += '<br/>'+item.position+' of '+album_count.toString();
		item.album_id = album.gphoto$id.$t;
		item.album_title = album.clean_title;
		return item;
	}
	
	function get_album_photos(album,albums_array,total_count)
	{
		//$.logThis('get_album_photos ' + album.link[0].href);
		var photo_feed = album.link[0].href;
		$.ajax({
			dataType : "jsonp",
			error : function() {
				$.logThis('error - photos from album ' + album.link[0].href + 'could not be loaded');
			},
			cache : false,
			url : photo_feed,
			success : function(data) {
				var cur_items = {};
				var album_count = 0;
				var album_thumb;
				$.each(data.feed.entry, function(i, item) {
					if(item.summary.$t != 'thumb')
					{
						album_count++;
						item.position = album_count.toString();
						item.order_by = album.order_by;
						all_photos_object[item.gphoto$id.$t] = item;
					}
					else
					{
						album_thumb = item;
					}
				});
				
				$.each(data.feed.entry, function(i, item) {
					if(item.summary.$t != 'thumb')
					{
						item = format_photo(item,album,album_count);
						cur_items[i] = item;
						if(item.media$group.media$content[1] && item.media$group.media$content[1].medium == 'video')
						{
							//replace video with thumbnail and set title
							item.media$group.media$thumbnail[0].url = album_thumb.media$group.media$thumbnail[0].url;
							item.clean_title = album.clean_title;
						}
						all_photos.push(item);
						
					}
				});
				
				album.info += album_count.toString();
				album.photos = cur_items;
				albums_array.push(album);
				albums_object[album.gphoto$id.$t] = album;
				if((commissioned_albums.length + personal_albums.length) == total_count)
				{
					$('#wrapper').height('');
					
					boo_all_photos_loaded = true;
					//sort albums
					commissioned_albums.sort(sort_albums);
					personal_albums.sort(sort_albums);
					//sort all photos
					all_photos.sort(sort_albums);
					
					//$.logThis(personal_albums);
					$.logThis('get_album_photos: all photos loaded. fullpage: ' + full_page + ' ' + boo_home_loaded);
					if(!full_page)
					{
						//full_page = window.location.hash;
					}
					if(((!full_page || full_page == '#home') && !boo_home_loaded) ||
							(full_page && full_page != '#home'))
					{
						$("#wrapper").trigger('show_page_in');
					}
				}
				
			}
		});
	}
	
	function sort_albums(a,b)
	{
		if(!parseInt(a) && !parseInt(b.order_by))
		{
			return 0;
		}
		if(parseInt(a.order_by) < parseInt(b.order_by))
		{
			return -1;
		}
		if(parseInt(a.order_by) == parseInt(b.order_by) && 'position' in a && 'position' in b)
		{
			if(parseInt(a.position) < parseInt(b.position))
			{
				return -1;
			}
			else
			{
				return 1;
			}
		}
		return 1;
	}

	function show_page(dir) {
		
		if(!boo_all_photos_loaded)
		{
			var screen_height = (checker.iphone || checker.ipad) ? window.innerHeight : $(window).height();
			$('#wrapper').height(screen_height - $('#nav').height()).css('background','url("css/images/loader.gif") no-repeat center center');
		}
		else
		{
			$('#wrapper').height('').css('background','none');
		}
		
		if (dir == 'out')
			$('#content').removeClass(page);
		else
		{
			if(new_page)
			{
				page = new_page;
			}
			new_page = null;
			$('#content').addClass(page);
		}
		$.logThis('show page ' + page + ' ' + dir);
		switch (page) {
			case 'home':
			default:
				$.logThis('Home '+dir+'? ' + boo_home_loaded);
				if (dir == 'in' && !boo_home_loaded)
					build_home();
				else if(dir == 'out' && boo_home_loaded)
				{
					$.logThis('Home out?');
					destroy_home();
				}
				else
				{
					destroy_home();
				}
				break;
			case 'commissioned':
				$.logThis('com in out? '+dir + ' ' + boo_all_photos_loaded);
				if(dir == 'in' && boo_all_photos_loaded)
				{
					$.logThis('com in ?' + boo_commissioned_loaded);
					if(arr_hash.length == 1 && !boo_commissioned_loaded)
					{
						build_commissioned();
					}
					else if(arr_hash.length == 2 && !boo_commissioned_loaded)
					{
						build_commissioned(arr_hash[1]);
					}
					else
					{
						$.logThis('com what else?' );
					}
				}
				else if(dir == 'out')
				{
					$.logThis('com out ?' + boo_commissioned_loaded);
					if(boo_commissioned_loaded)
					{
						destroy_commissioned(arr_hash[1]);
					}
				}
				break;
			case 'personal':
				$.logThis('personal ' + dir + ' boo_all_photos_loaded:' + boo_all_photos_loaded + ' boo_personal_loaded:' + boo_personal_loaded);
				if(dir == 'in' && boo_all_photos_loaded)
				{
					if(arr_hash.length == 1 && !boo_personal_loaded)
					{
						build_personal();
					}
					else if(!boo_personal_loaded && arr_hash.length == 2)
					{
						build_personal(arr_hash[1]);
						
					}
				}
				else
				{
					if(boo_personal_loaded)
					{
						destroy_personal(arr_hash[1]);
					}
				}
				break;
			case 'slider':
				$.logThis('show page slider ' + dir + ' boo_slider_loaded: ' + boo_slider_loaded);
				if (dir == 'in' && !boo_slider_loaded && boo_all_photos_loaded)
				{
					build_album(arr_hash[1],page);
				}
				else if(dir == 'out' && boo_slider_loaded)
				{
					destroy_album();
				}
				break;
			case 'overview':
				if (dir == 'in' && !boo_overview_loaded && boo_all_photos_loaded)
				{
					build_overview(arr_hash[1],page);
				}
				else if(dir == 'out' && boo_overview_loaded)
				{
					destroy_overview();
				}
				break;
			case 'all_albums':
				if (dir == 'in' && !boo_all_albums_loaded && boo_all_photos_loaded)
				{
					boo_all_albums_loaded = true;
					build_slider(albums_object[arr_hash[1]].photos,page);
				}
				else if(dir == 'out' && boo_all_albums_loaded)
				{
					boo_all_albums_loaded = false;
					destroy_slider();
				}
				break;
			
			case 'news':
				if (dir == 'in')
				{
					if(!boo_news_entry_loaded && arr_hash.length == 2)
					{
						build_news_entry();
					}
					else if(!boo_news_loaded && arr_hash.length == 1)
					{
						build_news();
					}
					else if(arr_hash.length == 1)
					{
						load_blog_entries();
					}
				}
				else
				{
					if(boo_news_entry_loaded)
					{
						destroy_news_entry();
					}
					else
					{
						destroy_news();
					}
				}
				break;
			case 'all':
				if (dir == 'in' && !boo_all_loaded && boo_all_photos_loaded)
					build_all();
				else if(dir == 'out' && boo_all_loaded)
					destroy_all();
				break;
			case 'info':
				if (dir == 'in' && !boo_info_loaded)
					build_info();
				else if(dir == 'out' && boo_info_loaded)
					destroy_info();
				break;
		}
	}
	
	/****************** Image Slider ****************/
	
	
	
	function alertStatus(e) {
	}
	
	function build_slider(arr_images, slider_type, active_slide)
	{
		
		$('#content').hide();
		$('#sub_nav').hide();
		var arr_tmp = new Array();
		$.each(arr_images, function(i, item) {
			arr_tmp.push(item);
		});
		
		arr_images = arr_tmp;
		var slider = $('<ul>').attr('id','slider');
		var screen_height = (checker.iphone || checker.ipad) ? window.innerHeight : $(window).height();
		var slider_wrapper = $('<div/>').attr('id','slider_wrapper')
					.css('background','url("css/images/loader.gif") no-repeat center center')
					.append($('<div>').addClass('slider_wrapper_inner').append(slider))
					.height(screen_height)
					.appendTo('body');
		
		
		//overlay with info
		var section_title = $('<a/>').attr('href','#'+arr_images[0].clean_section_url).append($('<h2/>').html(arr_images[0].clean_section));
		var album_title = $('<a/>').append($('<h2/>').addClass('album_title'));
		var overlay = $('<div/>').addClass('slider_info ' + arr_images[0].clean_section_url)
					.append($('<div/>').addClass('slider_info_wrapper')
										.append(section_title)
										.append(album_title)
										.append(share)
										);
		
		
		var resize_size = 200;
		var album_count = 0;
		var active_slide_count = 0;
	//	$.logThis('create slides: ' + active_slide.gphoto$id.$t);
	//	$.logThis(arr_images);
		
		
		//build fullscreen button
		var flashvars = {images: new Array(),image_width: new Array(), image_height: new Array()};
		$.each(arr_images, function(i, item) {
			flashvars.images.push(item.media$group.media$thumbnail[0].url);
			flashvars.image_width.push(item.gphoto$width.$t);
			flashvars.image_height.push(item.gphoto$height.$t);
		});
		var fullscreen_id = makeid();
		var fullscreen_button = $('<div/>').attr('id',fullscreen_id);
		var params = {allowFullScreen: true,
				allowScriptAccess: 'sameDomain',
				wmode:'transparent'};
		var attributes = {id: "fullscreen",
				  name: "fullscreen"};
		
		
		//create the slides
		var screen_height = (checker.iphone || checker.ipad) ? window.innerHeight : $(window).height();
		var screen_width = (checker.iphone || checker.ipad) ? window.innerWidth : $(window).width();
		$.each(arr_images, function(i, item) {
			//calculate image width and height to fit into slider window
			if(active_slide && item.gphoto$id.$t == active_slide.gphoto$id.$t)
			{
				active_slide_count = parseInt(i) + 1;
			}
			
			var media_item;
			
			//lets load a video
			if(item.media$group.media$content[1] && item.media$group.media$content[1].medium == 'video')
			{
				if(!checker_all){
					//change navigation
					$('.nav_home').stop().fadeTo(10,0);
				}
				var mediacontent = item.media$group.media$content;
				
				resize_size = calculate_slider_size(mediacontent[1].width,mediacontent[1].height,true,screen_width,screen_height - $('.nav_home').height());
				if(item.summary.$t)
				{
					//html5 player youtube
					//media_item = $('<iframe width="'+resize_size.width+'" height="'+resize_size.height+'" src="http://www.youtube.com/embed/'+item.summary.$t+'" frameborder="0" allowfullscreen></iframe>');
					//vimeo player
					media_item = '<iframe src="http://player.vimeo.com/video/'+item.summary.$t+'?color=ffffff&amp;byline=0&amp;hd=1" width="'+resize_size.width+'" height="'+resize_size.height+'" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>';
				}
				else
				{
					if(resize_size.width > 960)
					{
						resize_size.width = 960;
						resize_size.height = 616;
					}
					
					var my_video_url = '';
					for(var k = 1; k<mediacontent.length;k++)
					{
						//$.logThis(mediacontent[k]);
						switch(mediacontent[k].width)
						{
							case 400:
								my_video_url += encodeURIComponent('5|' + mediacontent[k].url).replace(/%2C/g,"%252C");
								break;
							case 640:
								my_video_url += encodeURIComponent('34|' + mediacontent[k].url).replace(/%2C/g,"%252C");
								break;
							case 854:
								my_video_url += encodeURIComponent('35|' + mediacontent[k].url).replace(/%2C/g,"%252C");
								break;
							case 1280:
								my_video_url += encodeURIComponent('22|' + mediacontent[k].url).replace(/%2C/g,"%252C");
								break;
							case 1920:
								my_video_url += encodeURIComponent('37|' + mediacontent[k].url).replace(/%2C/g,"%252C");
								break;
						}
						if(k < mediacontent.length-1)
						{
							my_video_url +='%2C';
						}
					}
					//my_video_url = '37%7Chttp%3A%2F%2Fv9.nonxt3.googlevideo.com%2Fvideoplayback%3Fid%3D1f6a1c0cbc675e91%26itag%3D37%26begin%3D0%26len%3D2147483647%26app%3Dpicasa%26et%3DINVALID%26el%3DINVALID%26ip%3D0.0.0.0%26ipbits%3D0%26expire%3D2893998249%26sparams%3Did%252Citag%252Cip%252Cipbits%252Cexpire%26signature%3D2DF61CFE6C52EAFD13B2268BAEF0E70269FF7244.596FAE2BE5F5C783DD29548C7882F411B56CC284%26key%3Dck1%2C22%7Chttp%3A%2F%2Fv3.nonxt8.googlevideo.com%2Fvideoplayback%3Fid%3D1f6a1c0cbc675e91%26itag%3D22%26begin%3D0%26len%3D2147483647%26app%3Dpicasa%26et%3DINVALID%26el%3DINVALID%26ip%3D0.0.0.0%26ipbits%3D0%26expire%3D2893998249%26sparams%3Did%252Citag%252Cip%252Cipbits%252Cexpire%26signature%3D58F1D1DFDCE322C9CAEF011BC8F6BA3545A36532.44D7100222934FA45C7FACBF413A1FE4D41165A9%26key%3Dck1%2C35%7Chttp%3A%2F%2Fv23.nonxt3.googlevideo.com%2Fvideoplayback%3Fid%3D1f6a1c0cbc675e91%26itag%3D35%26begin%3D0%26len%3D2147483647%26app%3Dpicasa%26et%3DINVALID%26el%3DINVALID%26ip%3D0.0.0.0%26ipbits%3D0%26expire%3D2893998249%26sparams%3Did%252Citag%252Cip%252Cipbits%252Cexpire%26signature%3D75DA733CC7E74D76090908E1743BE5F777ECA278.3A8E5606AEE62448D5591E5F3E1457AA226AD5AA%26key%3Dck1%2C34%7Chttp%3A%2F%2Fv11.nonxt7.googlevideo.com%2Fvideoplayback%3Fid%3D1f6a1c0cbc675e91%26itag%3D34%26begin%3D0%26len%3D2147483647%26app%3Dpicasa%26et%3DINVALID%26el%3DINVALID%26ip%3D0.0.0.0%26ipbits%3D0%26expire%3D2893998249%26sparams%3Did%252Citag%252Cip%252Cipbits%252Cexpire%26signature%3D21FAD3D2D377E54CB3E475B8AD0213A3FD876129.313AFC2688CD4A26D20A1503CB38AD92082472B8%26key%3Dck1%2C5%7Chttp%3A%2F%2Fv14.nonxt5.googlevideo.com%2Fvideoplayback%3Fid%3D1f6a1c0cbc675e91%26itag%3D5%26begin%3D0%26len%3D2147483647%26app%3Dpicasa%26et%3DINVALID%26el%3DINVALID%26ip%3D0.0.0.0%26ipbits%3D0%26expire%3D2893998249%26sparams%3Did%252Citag%252Cip%252Cipbits%252Cexpire%26signature%3D8FB910E14305AC4CB89843482C269D37F854F05.25ECC60DF1D6597BFE47445805D3CD6E8ED9FBDD%26key%3Dck1&amp;';
					
					media_item = $('<embed width="'+resize_size.width+'" height="'+resize_size.height+'" style="width: '+resize_size.width+'px; height: '+resize_size.height+'px;" '+
							'src="http://www.youtube.com/get_player?enablejsapi=1" type="application/x-shockwave-flash" '+
							'allowfullscreen="true" '+
							'allowscriptaccess="always" '+
							'bgcolor="#fff" '+
							'scale="noScale" '+
							'wmode="opaque" '+
							'flashvars="fs=1'+
									'&amp;hl=en'+
									'&amp;autoplay=1'+
									'&amp;ps=picasaweb'+
									'&amp;fmt_list=37%2F1920x1080%2F9%2F0%2F115%2C22%2F1280x720%2F9%2F0%2F115%2C35%2F854x480%2F9%2F0%2F115%2C34%2F640x360%2F9%2F0%2F115%2C5%2F400x226%2F7%2F0%2F0'+
									'&amp;fmt_stream_map='+my_video_url+
									'&amp;playerapiid=uniquePlayerId'+
									'&amp;video_id=picasacid'+
									'&amp;t=1'+
									'&amp;vq=large'+
									'&amp;auth_timeout=86400000000">');
				}
				
				
				$('<li/>').append(media_item).appendTo(slider);
				
				var top_video = (screen_height - $('.nav_home').height() - resize_size.height)/2 + $('.nav_home').height();
				if(top_video > 0)
				{
					slider.css('position','absolute');
					slider.css('top',top_video+'px');
				}
			}
			else
			{
				//change navigation
				$('.nav_home').stop().fadeTo(10,0);
				
				//resize all images to browser size
				slider.css('visibility','hidden');
				resize_size = calculate_slider_size(item.gphoto$width.$t,item.gphoto$height.$t,false,screen_width,screen_height);
				var tmstamp = new Date().getTime();
				var str_url = item.media$group.media$thumbnail[0].url.replace('s72',resize_size) + '?' + tmstamp;
				media_item = $('<img/>').addClass('slider_image').attr('src',str_url);
				//$.logThis('Resize Image: ' + str_url);
				
				//add overlay
				var img_overlay = overlay.clone();
				if(item.summary.$t)
				{
					img_overlay.find('.slider_info_wrapper').append($('<p/>').html(item.summary.$t));
				}
				var str_current_link = 'http://' + window.location.hostname + '/slider-'+item.gphoto$id.$t;
				$.logThis(item);
				var facebook_link = add_facebook_share(str_current_link,item.summary.$t,item.summary.$t,'image');
				img_overlay.find('.facebook').attr('href',facebook_link);
				img_overlay.find('.twitter').attr('href',img_overlay.find('.twitter').attr('href') + str_current_link);
				
				img_overlay.find('.album_title').html(item.album_title);
				img_overlay.find('.album_title').parent('a').attr('href','#overview-' + item.album_id).click(function(){
					change_page('#overview-' + item.album_id);
					});
				
				
				
				
				//add to slider list
				$('<li/>').append(media_item)
							.append(img_overlay)
							.appendTo(slider);
				
			}
			
			
			album_count++;
		});
		
		if(checker.iphone || checker.ipad)
		{
			$('.slider_info_wrapper h2').css('font-size','1.6em');
		}
		
		
		//resize slider on window resize
		
		$(window).bind('resize.slider',function() {
			boo_resized = true;
			if($('#slider').data('AnythingSlider'))
			{
				var screen_height = (checker.iphone || checker.ipad) ? window.innerHeight : $(window).height();
				var screen_width = (checker.iphone || checker.ipad) ? window.innerWidth : $(window).width();
				$('#slider_wrapper').height(screen_height);
				$('#slider').data('AnythingSlider').startStop(false);
				$('#slider li:not(.cloned) img.slider_image').each(function(){
					
					var img = $(this);
					var parent = img.parent();
					//var img_overlay = parent.find('.slider_info');
					var resize_size = calculate_slider_size(img.width(), img.height(),true,screen_width,screen_height);
					var margin = 0;
					if(screen_height - resize_size.height > 0)
					{
						margin = (screen_height - resize_size.height)/2;
					}
					img.css('margin-top',margin + 'px');
					
					img.height(resize_size.height);
					parent.height(resize_size.height + margin);
					img.width(resize_size.width);
					parent.width(resize_size.width);
					
					//position slider info over image
					var slider_top = $('.nav_home').height() > margin ? $('.nav_home').height() : margin;
					img.next('.slider_info').css('padding-top',slider_top);
					
					//img.parent().replaceWith($('<li/>').append(img).append(img_overlay));
				});
				$('#slider').height(resize_size.height);
				$('#slider').anythingSlider({autoplay: false});
			}
		});
		
		if($('#slider img.slider_image').length == 0)
		{
			$.logThis('no slideshow');
			if(checker_all)
			{
				
			}
			else
			{
				$('#slider').find('iframe').hover(function(e){
					$('.nav_home').stop().fadeTo('fast',1);
				},function(){
					$('.nav_home').stop().fadeTo('fast',0);
				});
			}
		}
		
		var load_count = 0;
		$('#slider img.slider_image').load(function(){
			load_count++;
			//$.logThis('Slider image loaded: ' + $(this).width());
			if(load_count == album_count)
			{
				$.logThis('SLIDER IMAGES LOADED!');
				$('#slider').css('visibility','visible').anythingSlider({
					animationTime	: checker_all ? 100 : 400,
					expand      	: false,
					autoPlay    	: false,
					resizeContents	: false,
					startPanel		: active_slide_count,
					hashTags		: false,
					buildNavigation	: false,
					buildStartStop	: false,
					infiniteSlides	: false,
					stopAtEnd		: true,
					onSlideBegin:	function(){
					},
					onSlideComplete     	: function(slider){
						//move fullscreen button to active slide
						var active = $('.activePage').find('.share');
						$('#fullscreen').insertBefore(active);
						
						 check_slider_resize();
							
					},
					onInitialized	: function(e, slider) {
						
						$.logThis('slider onInitialized');

						slider_wrapper.css('background','none');
						
						//set the overall slider dimension to not break chrome
						//reinitialize for chrome?
						$(window).trigger('resize.slider');
				        
				        
						//add full screen button
						if(!checker.iphone && !checker.ipad)
						{
							$('.activePage').find('.share').before(fullscreen_button);
							//$.logThis('set pixels: ' +$('.share_text').height() + ' ' + $('.share_text').css('font-family'));
							flashvars.font_size = 13;
							swfobject.embedSWF("../swf/fullscreen.swf", 
									fullscreen_id,
									"88", 
									"20", 
									"10.0.0",
									null, 
					                flashvars, 
					                params, 
					                attributes,
					                alertStatus
					                );
						}
						
						var over_time;
						//overlay mouseover action
						/* PHONE TOUCH MOVEMENT START */
						if(checker_all  && $('#slider img.slider_image').length > 0)
						{
							$('.arrow').remove();
							
							var time = 1000, // allow movement if < 1000 ms (1 sec)
				            range = 10,  // swipe movement of 50 pixels triggers the slider
				            check_x = 0, x, t, r, dir;
							$('#slider_wrapper').bind('touchstart', function(e){
								e.preventDefault();
								var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
								x = touch.pageX;
								t = e.timeStamp;
							});
							
							$('#slider_wrapper').bind('touchmove',function(e){
								e.preventDefault();
								if(!slider.$wrapper.is(':animated'))
								{
									var slider_pos = parseInt($('#slider').css('left').replace('px',''));
									var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
									r = Math.abs(touch.pageX - x);
									if (touch.pageX < x ) {
										check_x -= r;
										var newleft = (slider_pos - r).toString() + 'px'; 
										dir = 'left';
										x = touch.pageX;
										$('#slider').css('left',newleft);
					                }
									if (touch.pageX > x) {
										check_x += r;
					                	var newleft = (slider_pos + r).toString() + 'px'; 
					                	dir = 'right';
					                	x = touch.pageX;
					                }
									
									$('#slider').css('left',newleft);
									
									if(Math.abs(check_x) < range)
									{
										dir = 'nope';
									}
								}
							});
							
							
							$('#slider_wrapper').bind('touchend', function(e){
								$.logThis('touchend');
								e.preventDefault();
								check_x = 0;
								
								if (dir == 'left') {
									slider_moved = true;
									show_nav_home(false);
									$('.slider_info').css('visibility','hidden');
				                    slider.goForward();
				                }
								else if (dir == 'right') {
									slider_moved = true;
				                    slider.goBack();
				                    show_nav_home(false);
				                    $('.slider_info').css('visibility','hidden');
				                }
								else
								{
									show_nav_home(true);
									slider.gotoPage(slider.currentPage);
								}
								dir = 'nope';
							});
							
							$('.panel a').doubletap(function(event){  
								
									},
								    /** touch-click callback (touch) */
								    function(event){ 
										$.logThis($(event.currentTarget).attr('href').search('http'));
										if($(event.currentTarget).attr('href').search('http') == 0)
										{
											window.location = $(event.currentTarget).attr('href');
										}
										else
										{
											window.location.hash = $(event.currentTarget).attr('href');
										}
									},
								    /** doubletap-dblclick delay (default is 500 ms) */
								    400
								);
							$('.panel').doubletap(
							    /** doubletap-dblclick callback */
							    function(event){
							    	var e = event.originalEvent;
							    	e.preventDefault ? e.preventDefault() : e.returnValue = false;
							    	$.logThis('doubletab');
							        var info = $(event.currentTarget).children('.slider_info');
							    	if(info.css('visibility') == 'visible')
							    	{
							    		show_nav_home(false);
							    		info.css('visibility','hidden');
							    	}
							    	else
							    	{
							    		show_nav_home(true);
							    		info.css('visibility','visible');
							    	}
							    },
							    /** touch-click callback (touch) */
							    function(event){
							    	var e = event.originalEvent;
							    	e.preventDefault ? e.preventDefault() : e.returnValue = false;
							    	 var info = $(event.currentTarget).children('.slider_info');
							    	$.logThis('singeltab' + info.css('visibility') + info.is(':visible'));
							       
							    	if(info.css('visibility') == 'visible')
							    	{
							    		show_nav_home(false);
							    		info.css('visibility','hidden');
							    	}
							    	else if(!slider_moved)
							    	{
							    		show_nav_home(true);
							    		info.css('visibility','visible');
							    	}
							    	else
							    	{
							    		slider_moved = false;
							    	}
							    },
							    /** doubletap-dblclick delay (default is 500 ms) */
							    400
							);
						}
						/* PHONE TOUCH MOVEMENT END */
						else
						{
								$('.panel').hover(function(e){
									check_slider_resize();
									$(this).children('.slider_info').css('visibility','visible');
									show_nav_home(true);
								},function(){
									$(this).children('.slider_info').css('visibility','hidden');
									show_nav_home(false);
								});
						}
			        
				    }
				});
			}
		});
		
		
		
	}
	
	function show_nav_home(boo_show)
	{
		$.logThis('SHOW NAV ' + boo_show);
		if(boo_show)
		{
			$('.nav_home').stop().fadeTo('fast',1);
		}
		else
		{
			$('.nav_home').stop().fadeTo('fast',0);
		}
			
	}
	
	function check_slider_resize()
	{
		if(boo_resized)
		{
			var load_count = 0;
			var slider_count = $('#slider li:not(.cloned) img.slider_image').length;
			$('#slider li:not(.cloned) img.slider_image').each(function(){
				
				var img = $(this);
				var screen_height = (checker.iphone || checker.ipad) ? window.innerHeight : $(window).height();
				var screen_width = (checker.iphone || checker.ipad) ? window.innerWidth : $(window).width();
				var resize_size = calculate_slider_size(img.width(), img.height(), false,screen_width,screen_height);
				var arr_url = img.attr('src').split('/');
				var old_resize  = arr_url[arr_url.length-2];
				var str_src = img.attr('src').replace(old_resize,resize_size);
				//$.logThis('RESIZE TO from:' + old_resize+' new:'+resize_size);
				if(old_resize != resize_size)
				{
					img.attr('src',str_src).load(function(){
						load_count++;
						if(slider_count == load_count)
						{
							$.logThis('ALL LOADED! '+$(this).attr('src'));
							$('#slider').anythingSlider({autoPlay    	: false});
							$('#slider').data('AnythingSlider').startStop(true);
						}
						
					});
				}
			});
			boo_resized = false;
		}
	}
	
	function destroy_slider()
	{
		$.logThis('destroy_slider');
		$(window).unbind('resize.slider');
		$('#content').show();
		$('#sub_nav').show();
		$('#slider_wrapper').remove();
		$("#wrapper").trigger('show_page_in');
	}

	/****************** SUB NAVIGATION *********************/

	function build_sub_nav(str_title,str_class,arr_links)
	{
		$('#sub_nav ul').stop();
		$('#sub_nav').removeClass();
		var nav_title = $('<a/>').attr('href','#'+str_class).html(str_title);
		nav_title.click(function(){
			$.logThis('CLICKCLICK');
			$('.sub_nav_item a').removeClass('active');
		});
		var sub_nav = $('<ul/>').css('margin-top','-100px').append($('<li/>').addClass('nav_title').append(nav_title));
		if(arr_links)
		{
			for(var i=0; i<arr_links.length;i++)
			{
				var a_link = $('<a/>').attr('href','#'+arr_links[i].link).html(arr_links[i].title);
				//$.logThis('xx ' + full_new_page +' gg ' + arr_links[i].link);
				if(full_new_page == '#'+arr_links[i].link)
				{
					a_link.addClass('active');
				}
				sub_nav.append($('<li/>').addClass('sub_nav_item').append(a_link));
				a_link.click(function(){
					$('.sub_nav_item a').removeClass('active');
					$(this).addClass('active');
				});
			}
		}
		$('#sub_nav').addClass('sub_'+str_class).html(sub_nav);
		$.logThis('SUBNAV? ' + str_title);
		
		sub_nav.animate({marginTop:0},200);
	}
	function destroy_sub_nav(delay_out)
	{
		$('#sub_nav ul').stop();
		if(!delay_out)
		{
			delay_out = 0;
		}
		$('#sub_nav ul').delay(delay_out).animate({marginTop:-100},200,function(){
			$(this).removeClass().html('');
		});
	}
	
	
	/************** GALLERY ****************/
	var all_pagination_items;
	function build_gallery(column_count,albums,type,filter,boo_mouse_action,int_pagination,boo_no_clean)
	{
		$.logThis('build_gallery start');
		$.logThis($('.blog_item').length);
		
		if(!boo_no_clean)
		{
			$('#content').html('');
		}
		$(document).scrollTop(0);
		cur_gallery_type = filter;
		boo_gallery = true;
		$(window).resize(function() {
			$('.img_wrap').each(function(){
				var img = $(this).children('img');
				$(this).height(img.height());
				$(this).children('.img_overlay').css('left',(img.width()*-1) - 1);
			});
		});
		
		// build columns
		gallery_columns = {};
		gallery_scroll_active = {};
		for(var i = 1; i<=column_count; i++)
		{
			gallery_columns['col_' + i] = $('<div/>').attr('id','col_' + i).addClass('col_' + column_count).appendTo('#content');
			gallery_scroll_active['col_' + i] = true;
			if(column_count == i)
			{
				gallery_columns['col_' + i].addClass('last');
			}
		}
		
		
		
		// build gallery images
		
		
		arr_photos = new Array();
		arr_films = new Array();
		var final_albums = new Array();
		if(filter)
		{
			$.each(albums, function(i, item) {
				if((filter == 'photo' && (item.title.$t.indexOf("pv-") == 0 || item.title.$t.indexOf("cv-") == 0)) ||
						(filter == 'film' && (item.title.$t.indexOf("pp-") == 0 || item.title.$t.indexOf("cp-") == 0)))
					{
						
					}
				else
					{
					final_albums.push(item);
					}
			});
		}
		else
		{
			$.each(albums, function(i, item) {
				final_albums.push(item);
			});
		}
		//do we have lazy load?
		all_pagination_items = final_albums;
		if(int_pagination)
		{
			cur_pagination_index = int_pagination;
			all_pagination_items = final_albums;
			var total_pagination_count = 0;
		    for (var key in final_albums) {
		        if (final_albums.hasOwnProperty(key)) total_pagination_count++;
		    }
			var pagination_albums = new Array();
			var l = 0;
			for(var pag_item in final_albums)
			{
				pagination_albums.push(final_albums[pag_item]);
				l++;
				if(l >= int_pagination)
				{
					break;
				}
				
			}
			final_albums = pagination_albums;
		}
		

		//BUILD GALLERY COLUMNS AND LOAD ITEMS START
		gallery_build_count = 0;
		var j = 1;
		var total_gallery_count = 0;
	    for (var key in final_albums) {
	        if (final_albums.hasOwnProperty(key)) total_gallery_count++;
	    }
		$.each(final_albums, function(i, item) {
			
			//what column are we in?
			if(j > column_count)
			{
				j = 1;
			}
			cur_col = gallery_columns['col_' + j];
			j++;
			build_gallery_item(item,i,column_count,cur_col,total_gallery_count,type,boo_mouse_action);
		});
		
		//BUILD GALLERY COLUMNS END
		
		
		//DO LAZY LOAD
		if(int_pagination)
		{
			$(window).bind('scroll.gallery', function() {
				if(boo_gallery_animated_in && !boo_news_loaded)
				{
					var columns = $('.col_' + column_count);
					columns.each(function(){
						var jqTargetElement = $(this);
						if(jqTargetElement.attr('id') && (gallery_scroll_active[jqTargetElement.attr('id')] || checker_all))
						{
							var topOffset = checker.iphone ? window.pageYOffset : $(document).scrollTop();
							var win_height = window.innerHeight ? window.innerHeight : $(window).height();
							var fire = false;
							if ( jqTargetElement.data('onScrollBeyond-disabled') == true ) {
									return; 
							}
							if ( settings.fireOnBeyondElement ) {
								// if element has scrolled off the screen, even if other elements exist below it
								if ( topOffset + win_height > (jqTargetElement.position().top + jqTargetElement.height()) ) {
									fire = true;
								}
							
							}
							
							if ( !fire && settings.fireOnDocEnd ) {
							
								var amt_scrolled = topOffset - jqTargetElement.position().top ;
								
								// if the amount of the element we already scrolled beyond + its top position on the document + the window height + some buffer is greater than the total doc height
								if ( (amt_scrolled + jqTargetElement.position().top + win_height + settings.buffer) > jQuery(document).height() ) {
									fire = true;
								}
							}
							
							if ( fire || checker_all ) {
								if(total_pagination_count >= cur_pagination_index && all_pagination_items[cur_pagination_index])
								{
									var scroll_filter = arr_hash[1] == 'photo' || arr_hash[1] == 'film' ? arr_hash[1] : null;
									if((scroll_filter == 'photo' && (all_pagination_items[cur_pagination_index].title.$t.indexOf("pp-") == 0 || all_pagination_items[cur_pagination_index].title.$t.indexOf("cp-") == 0)) ||
											(scroll_filter == 'film' && (all_pagination_items[cur_pagination_index].title.$t.indexOf("pv-") == 0 || all_pagination_items[cur_pagination_index].title.$t.indexOf("cv-") == 0)) ||
											scroll_filter == undefined || !scroll_filter
										)
									{
										$.logThis('LOAD NEW GALLERY ITEM ' + jqTargetElement.attr('id'));
										//deactivate
										gallery_scroll_active[jqTargetElement.attr('id')] = false;
										//load item
										var preload = $('<div/>').addClass('preloader').attr('id',jqTargetElement.attr('id')+'_loader');
										jqTargetElement.append(preload);
										build_gallery_item(all_pagination_items[cur_pagination_index],cur_pagination_index,column_count,jqTargetElement,1,type,boo_mouse_action,true);
									}
									
									cur_pagination_index++;
								}
							}
						}
					});
				}
			});      
			//$(window).trigger("scroll.gallery");
		}
		
	}
	
	function build_gallery_item(item,i,column_count,cur_col,total_gallery_count,type,boo_mouse_action,boo_single)
	{
		//$.logThis('build_gallery_item ');
		
		//create image wrap
		item.wrap_id = makeid();
		var img_wrap = $("<div/>").addClass('img_wrap').attr('id',item.wrap_id)
						.css('visibility','hidden')
						.appendTo(cur_col);
		
		
		//add the correct margin to the image wrap
		var marginRight = $('.col_' + column_count).css('margin-right');
		if(marginRight == '0px')
		{
			marginRight = '15px';
		}
		if(marginRight.search('%') != -1)
		{
			//calculate the spacing for silly chrome browser
			marginRight = $('.col_' + column_count).parent().width()/100 * parseInt(marginRight.replace('%',''));
		}
		img_wrap.css('marginBottom',marginRight);
		
		
		//$.logThis(item.gphoto$width);
		//lets see if we have content or image
		if(item.gphoto$width && item.gphoto$width.$t == 1)
		{
			//CONTENT
			gallery_build_count++;
			//take text content
			img_wrap.append(item.summary.$t);
			if(total_gallery_count == gallery_build_count)
			{
				//animate in for first time
				animate_gallery_in($('.img_wrap'));
			}
		}
		else
		{
			//IMAGE
			var resize_width = cur_col.width();
			var str_replace;
			if(type == 'albums')
			{
				str_replace = 's160-c';
			}
			else
			{
				str_replace = 's72';
			}
			var tmstamp = new Date().getTime();
			var str_url = item.media$group.media$thumbnail[0].url.replace(str_replace,'s'+resize_width) + '?' + tmstamp;
			var img = $("<img/>").attr("src", str_url);
			//position and move images once they are loaded
			if(boo_single)
			{
				img.load(function() {
					
					var pic_real_width = this.width; // work for in memory images.
				    var pic_real_height = this.height; // work for in memory images.
				    var cur_img = $(this);
					var cur_wrap = cur_img.parent();
					cur_wrap.prev('.preloader').remove();
					cur_wrap.height(pic_real_height);
						cur_wrap.css('visibility','visible');
						//resize if portrait
						if(pic_real_width/pic_real_height < 1)
						{
							var new_resize_width = calculate_slider_size(pic_real_width,pic_real_height,false,pic_real_width);
							var new_src = $(this).attr('src').replace('s'+resize_width,new_resize_width);
							cur_img.attr('src',new_src).load(function(){
								//reactivate scroll lazy loading
								gallery_scroll_active[cur_wrap.parent().attr('id')] = true;
							});
						}
						else
						{
							//reactivate scroll lazy loading
							gallery_scroll_active[cur_wrap.parent().attr('id')] = true;
						}
				    });
				
			}
			else
			{
				img.load(function() {
					 	var pic_real_width = this.width; // work for in memory images.
				        var pic_real_height = this.height; // work for in memory images.
				        var cur_img = $(this);
						var cur_wrap = cur_img.parent();
						cur_wrap.height(pic_real_height);
						
						//resize if portrait
						if(pic_real_width/pic_real_height < 1)
						{
							var new_resize_width = calculate_slider_size(pic_real_width,pic_real_height,false,pic_real_width);
							var new_src = $(this).attr('src').replace('s'+resize_width,new_resize_width);
							cur_img.attr('src',new_src).load(function(){
								gallery_build_count++;
								if(total_gallery_count == gallery_build_count)
								{
									//animate in for first time
									animate_gallery_in($('.img_wrap'));
								}
							});
						}
						else
						{
							gallery_build_count++;
							if(total_gallery_count == gallery_build_count)
							{
								//animate in for first time
								animate_gallery_in($('.img_wrap'));
							}
						}
						
						
				    });
			}
				
			
			if(boo_mouse_action)
			{
				img_wrap.append($('<div/>').addClass('img_overlay').css('left',(resize_width*-1) - 3).attr('id',i+'_'+item.wrap_id)
						  .append($('<h2/>')
									.html(item.clean_title))
							.append($('<p/>').html(item.info)));
			}
							
			img_wrap.append(img);
		}
		
					
		arr_cur_gallery.push(img_wrap);
		
		
		//do some filtering preparation
		if(item.title.$t.indexOf("pp-") == 0 || item.title.$t.indexOf("cp-") == 0)
		{
			arr_photos.push(img_wrap);
		}
		else if(item.title.$t.indexOf("pv-") == 0 || item.title.$t.indexOf("cv-") == 0)
		{
			arr_films.push(img_wrap);
		}
		
		//add mouse events fore each image wrap
		if(boo_mouse_action)
		{
			var click_url = type == 'items' ? 'slider' : 'overview';
			
			if(checker_all)
			{
				var boo_is_scrolled = false;
				var t;
				$(window).bind('scroll.mobilegallery',function(){
					boo_is_scrolled = true;
					clearTimeout(t);
					t = setTimeout(function(){
						boo_is_scrolled = false;
					},500);
				});
				img_wrap.doubletap(
					    /** doubletap-dblclick callback */
					    function(event){
					    	
					    	$.logThis('double tab');
					    	var e = event.originalEvent;
					    	e.preventDefault ? e.preventDefault() : e.returnValue = false;
					    	if(!boo_is_scrolled)
					    	{
						    	/*var anim = $(event.currentTarget).children('.img_overlay');
						    	if(parseInt(anim.css('left').replace('px','')) >= 0)
						    	{
									anim.stop().animate({left:anim.width()},{queue:false,duration:200,complete:function(){
										$(this).css('left',(anim.width()*-1)-3);
									}});
						    	}*/
								var str_hash = '#'+click_url+'-' + item.gphoto$id.$t;
								window.location.hash = str_hash;
					    	}
					    },
					    /** touch-click callback (touch) */
					    function(event){
					    	var e = event.originalEvent;
					    	e.preventDefault ? e.preventDefault() : e.returnValue = false;
						    	$.logThis('single tab');
					    	if(!boo_is_scrolled)
					    	{
					    		$.logThis('single tab not scrolled');
								var str_hash = '#'+click_url+'-' + item.gphoto$id.$t;
								window.location.hash = str_hash;
					    	}
					    	return false;
					    },
					    /** doubletap-dblclick delay (default is 500 ms) */
					    400
					);
			}
			else
			{
				
				img_wrap.hover(function(){
						var anim = $(this).children('.img_overlay');
						anim.stop().animate({left:0},{queue:false,duration:200});
					},function(){
						var anim = $(this).children('.img_overlay');
						anim.stop().animate({left:anim.width()},{queue:false,duration:200,complete:function(){
							$(this).css('left',(anim.width()*-1)-3);
						}});
					});
				img_wrap.click(function(){
					var anim = $(this).find('.img_overlay');
					anim.stop().animate({left:anim.width()},{queue:false,duration:200,complete:function(){
						$(this).css('left',(anim.width()*-1)-3);
					}});
					var str_hash = '#'+click_url+'-' + item.gphoto$id.$t;
					window.location.hash = str_hash;
				});
				
				
			}
				
		}
		
	}
	
	function do_animate_in(items)
	{
		
		var total_count = items.length;
		var start_height = $(window).height();
		$.logThis('animaitemste_gallery_in');
		$('#content').height($(window).height());
		//position - wait for sub nav to move in
		items.delay(300).each(function(i){
				//lets check if its in view
				var pos = $(this).position();
				var item_x = pos.left;
				var item_y = pos.top;
				$(this).css('top',item_y + start_height);
				$(this).css('left',item_x);
				$(this).width($(this).width());
				$(this).height($(this).height());
		})
		.css('position','absolute')
		.css('visibility','visible');
		var count = 0;
		items.each(function(i){
				//lets check if its in view
				var in_delay = 0;
				var pos = $(this).position();
				var item_y = pos.top-start_height;
				$(this).css('visibility','visible').delay(in_delay).animate({top:item_y},random_from_to(300, 700),function(){
					count++;
					if(count == total_count)
					{
						$('#content').height('');
						boo_gallery_animated_in = true;
						$.logThis('galllery is animated in');
						items.css('position','relative');
						items.css('top','');
						items.css('left','');
						items.css('width','100%');
						items.each(function(){
							if($(this).children('.img_overlay').length == 0)
							{
								//readjust text boxes
								$(this).css('height','100%');
							}
						});
						//items.css('height','auto');
						$(".info_links").trigger('gallery_is_in');
						$(window).scroll();
					}
				});
			});
			
	}
	var animate_in_timeout;
	function animate_gallery_in(items)
	{
		$.logThis('animate_gallery_in');
		boo_gallery_animated_in = false;
		items.css('visibility','hidden');
		//wait for subnav to appear
		animate_in_timeout = setTimeout(function(){do_animate_in(items);},200);
	}
	
	
	function destroy_gallery(albums,filter)
	{
		$.logThis('unbind scroll gallery');
		$(window).unbind('scroll.gallery');
		all_pagination_items = new Array();
		//stop all in animation
		if(animate_in_timeout)
		{
			clearTimeout(animate_in_timeout);
		}
		$('.img_wrap').stop();
		$('.img_wrap').css('position','relative');
		$('.img_wrap').css('top','');
		$('.img_wrap').css('left','');
		$('.img_wrap').css('width','100%');
		
		$.logThis('destroy_gallery ' + filter);
		cur_gallery_type = null;
		arr_cur_gallery = new Array();
		boo_gallery = false;
		
		if(filter)
		{
			var final_albums = new Array();
			$.each(albums, function(i, item) {
				if((filter == 'photo' && (item.title.$t.indexOf("pp-") == 0 || item.title.$t.indexOf("cp-") == 0)) ||
						(filter == 'film' && (item.title.$t.indexOf("pv-") == 0 || item.title.$t.indexOf("cv-") == 0)))
					{
					final_albums.push(item);
					}
			});
			albums = final_albums;
		}
		var destroy_count = 0;
		
		var scroll_outs = new Array();
		$('.img_wrap').each(function(i){
			if(isScrolledIntoView($(this)))
			{
				scroll_outs.push($(this));
			}
		});
		//remove actions
		// set up action for images
		$('#content img').unbind('click');
		$('.img_wrap').unbind(mouseenterevent + ' mouseleave');
		var total_count = scroll_outs.length;
		$.logThis('destroy_gallery');
		$.logThis(scroll_outs);
		$.each(scroll_outs,function(i,item){
				$(this).delay(random_from_to(100, 500)).animate({marginTop:$(window).height()+500},random_from_to(200, 700),function(){
					destroy_count++;
					if(destroy_count == total_count)
					{
						$.logThis('DONE, all out, lets move stuff in again');
						$(document).scrollTop();
						$('.img_wrap').remove();
						$('#content').html('');
						$("#wrapper").trigger('show_page_in');
					}
				});
		});
		
		
	}
	
	
	function filter_gallery(albums,type)
	{
		$.logThis('filter_gallery' + cur_gallery_type + ' to ' + type);
		if(cur_gallery_type != type)
		{
			cur_gallery_type = type;
			switch(type)
			{
				case 'photo':
					filter_in_out(arr_films,arr_photos);
					break;
				case 'film':
					filter_in_out(arr_photos,arr_films);
					break;
				default:
					filter_in_out(null,albums);
					break;
			}
		}
	}
	
	function filter_in_out(arr_out,arr_in)
	{
		$.each(arr_out, function(i, out_item) {
			out_item.slideUp('slow');
		});
		$.each(arr_in, function(i, in_item) {
			in_item.delay(200).slideDown('slow');
		});
		
	}
	
	/************** Project overview ****************/
	
	function build_overview(id)
	{
		current_overview_id = id;
		boo_overview_loaded = true;
		var cur_album = albums_object[id];
		var arr_items = albums_object[id].photos;

		build_sub_nav(cur_album.clean_section,cur_album.clean_section_url);
		
		
		$('#content').css('margin-top',$(window).height());
		
		//album date
		arr_date = cur_album.published.$t.split('-');
		var date = $('<p>Year.<br/>'+arr_date[0]+'</p>');
		
		var blog_info = $('<div/>').addClass('blog_info col_4').append(date).append(share.clone());
		
		var article = $('<article/>').addClass('entry_wrapper clearfix')
		.append($('<h2/>').html(cur_album.clean_title));
		
		
		//album description
		if(albums_object[id].summary.$t)
		{
			var entry_content = $('<p>'+albums_object[id].summary.$t+'</p>');
			article.append($('<div/>').addClass('blog_entry col_4').append(entry_content));
		}
		
		article.append(blog_info)
			.prependTo('#content');	
			
		if(checker.iphone || checker.ipad)
		{
			$('.entry_wrapper h2').css('font-size','1.6em');
		}
		
		//twitter and facebook
		var str_current_link = 'http://' + window.location.hostname + '/overview-'+cur_album.gphoto$id.$t;
		var facebook_link = add_facebook_share(str_current_link,cur_album.clean_title,cur_album.summary.$t,'mult');
		blog_info.find('.facebook').attr('href',facebook_link);
		blog_info.find('.twitter').attr('href',blog_info.find('.twitter').attr('href') + str_current_link);
		
		//add class to content div
		$('#content').addClass(cur_album.clean_section_url);
		$('#content').animate({marginTop:0},300,function(){
			
		});
		build_gallery(4,arr_items,'items',false,true,10,true);
	}
	
	function destroy_overview()
	{
		$.logThis('destroy_overview');
		
		boo_overview_loaded = false;
		var cur_album = albums_object[current_overview_id];
		
		destroy_gallery(cur_album.photos);
		//remove class from content div
		//add class to content div
		$('#content').removeClass(cur_album.clean_section_url);
		destroy_sub_nav(500);
		$('.entry_wrapper').delay(200).animate({marginTop:-500},300,function(){$(this).remove();});
		
	}
	
	
	/************** Home ****************/
	
	function build_home() {
		$.logThis('build_home');
		boo_home_loaded = true;
		var bg_feed = picasa_feed + '/album/backgrounds?alt=json&kind=photo';
		// load random background image
		$.ajax({
					dataType : "jsonp",
					error : function() {
						$.logThis('error - backgrounds album could not be loaded');
					},
					cache : false,
					url : bg_feed,
					success : function(data) {
						
						$.logThis('background loaded');
						var rand = random_from_to(0, data.feed.entry.length - 1);
						var img = data.feed.entry[rand];
						var new_width = $(window).width()+200;
						if(new_width > 2000)
						{
							new_width = 2000;
						}
						var bg_img = img.media$group.media$thumbnail[0].url.replace('s72','s'+new_width);
						$('#wrapper').css('background','none');
						$.backstretch(bg_img, {
							speed : 150
						},function(){
						});
					}
				});
	}

	function destroy_home() {
		$.logThis('destroy_home');
		boo_home_loaded = false;
		$.backstretch('',{speed:300},function(){$("#wrapper").trigger('show_page_in');});
	}
	
	/************** PERSONAL ****************/
	
	function build_personal(filter) {
		
		boo_personal_loaded = true;
		// build subnav
		build_sub_nav('Personal','personal',new Array({title: 'Photo',link:'personal-photo'},{title: 'Film',link:'personal-film'}));
		build_gallery(3,personal_albums,'albums',filter,true,10);
		
	}
	function destroy_personal(filter) {
		$.logThis('destroy_personal ' + full_page + ' ' + full_new_page);
		if(full_page == null || !(full_page.search('personal') == 1 && full_new_page.search('personal') == 1))
		{
			destroy_sub_nav(400);
		}
		destroy_gallery(personal_albums,filter);
		boo_personal_loaded = false;
	}
	
	/* ALBUM VIEW */
	function build_album(id,type)
	{
		$.logThis('build_album' + id);
		boo_slider_loaded = true;
		if(albums_object[id] == undefined)
		{
			//lets see if we want a specific photo
			if(all_photos_object[id] == undefined)
			{
				change_page('home');
			}
			else
			{
				$.logThis('BUILD SLIDER WITH PHOTO SELECTED');
				$.logThis(albums_object[all_photos_object[id].album_id].photos.length);
				build_slider(albums_object[all_photos_object[id].album_id].photos,type,all_photos_object[id]);
			}
		}
		else
		{
			$.logThis('BUILD SLIDER WITH ALBUM SELECTED');
			build_slider(albums_object[id].photos,type);
		}
	}
	
	function destroy_album()
	{
		boo_slider_loaded = false;
		$('.nav_home').unbind(mouseenterevent +' mouseleave');
		destroy_slider();
	}
	
	/************** COMMISSIONED ****************/
	
	function build_commissioned(filter) {

		boo_commissioned_loaded = true;
		// build subnav
		build_sub_nav('Commissioned','commissioned',new Array({title: 'Photo',link:'commissioned-photo'},{title: 'Film',link:'commissioned-film'}));
		build_gallery(3,commissioned_albums,'albums',filter,true,10);
	}
	
	function destroy_commissioned(filter)
	{
		$.logThis('destroy_commissioned');
		boo_commissioned_loaded = false;
		if(full_page == null || !(full_page.search('commissioned') == 1 && full_new_page.search('commissioned') == 1))
		{
			destroy_sub_nav(400);
		}
		destroy_gallery(commissioned_albums,filter);
	}

	/************** NEWS ****************/

	function build_news() {
		$('#wrapper').css('background','none');
		$.logThis('build_news');
		boo_news_loaded = true;
		build_sub_nav('News','news');
		$(window).scrollTop(0);
		if(str_news_html)
		{
			$(str_news_html).find('.blog_item').css('position','');
			$('#content').html(str_news_html);
			//animate in
			animate_gallery_in($('.blog_item'));
		}
		else
		{
			$('<div/>').addClass('col_3').attr('id','col_1').appendTo('#content');
			$('<div/>').addClass('col_3').attr('id','col_2').appendTo('#content');
			$('<div/>').addClass('col_3 last').attr('id','col_3').appendTo('#content');
			load_blog_entries();
		}
			scroll_active = {col_1: true,col_2: true,col_3: true};
			$(window).bind('scroll.news', function() {
				$.logThis('SCROLL NEWS');
				if(boo_news_loaded && boo_gallery_animated_in)
				{
					$('.col_3').each(function(){
						var jqTargetElement = $(this);
						if(scroll_active[jqTargetElement.attr('id')])
							{
						var fire = false;
						
						if ( jqTargetElement.data('onScrollBeyond-disabled') == true ) {
							return; 
						}
						if ( settings.fireOnBeyondElement ) {
							// if element has scrolled off the screen, even if other elements exist below it
							if ( $(document).scrollTop() + $(window).height() > (jqTargetElement.position().top + jqTargetElement.height()) ) {
								fire = true;
							}
						
						}
						
						if ( !fire && settings.fireOnDocEnd ) {
						
							var amt_scrolled = $(document).scrollTop() - jqTargetElement.position().top ;
							
							// if the amount of the element we already scrolled beyond + its top position on the document + the window height + some buffer is greater than the total doc height
							if ( (amt_scrolled + jqTargetElement.position().top + jQuery(window).height() + settings.buffer) > jQuery(document).height() ) {
								fire = true;
							}
						}
						
						if ( fire ) {
							if(total_blog_entries >= cur_blog_index)
							{
								//deactivate
								scroll_active[jqTargetElement.attr('id')] = false;
								blogger_service.getBlogFeed(blog_feed+ '?max-results=1&start-index='+cur_blog_index,function(blogFeedRoot){
									 arr_blog_entries = blogFeedRoot.feed.getEntries();
									  if(!arr_blog_entries.length){
										$(window).unbind('scroll.news');
									    return;
									  }
									  else 
									  {
										  load_blog_entries(jqTargetElement);
									  }
									  scroll_active[jqTargetElement.attr('id')] = true;
									},handle_blog_error);
								cur_blog_index++;
							}
						}
							}
					});
				}
			});  
			
		
		
	}
	
	function destroy_news()
	{
		$.logThis('destroy_news');
		str_news_html = $('#content').html();
		$(window).unbind('scroll.news');
		destroy_sub_nav(400);
		
		//stop loading of items
		scroll_active = {col_1: false,col_2: false,col_3: false};
		var destroy_count = 0;
		$('.blog_item').each(function(i){
			//lets check if its in view
			var pos = $(this).position();
			var item_x = pos.left;
			var item_y = pos.top;
			$(this).css('top',item_y);
			$(this).css('left',item_x);
			$(this).width($(this).width());
			$(this).height($(this).height());
		});
		$('.blog_item').css('position','absolute');
		
		var in_view = new Array();
		$('.blog_item').each(function(i){
			if(isScrolledIntoView($(this)))
			{
				in_view.push($(this));
			}
			else
			{
				$(this).remove();
			}
		});
		var total_count = in_view.length;
		if(total_count == 0)
		{
			//scroll to the top
			$(window).scrollTop(0);
			//move nav to top
			$('#nav').css('top',0);
			$('.nav_bg').css('top',0);
			scroll_active = {col_1: true,col_2: true,col_3: true};
			$('#content').html('');
			$("#wrapper").trigger('show_page_in');
			boo_news_loaded = false;
		}
		$.each(in_view,function(i,item){
				//lets check if its in view
				var out_delay = random_from_to(10, 400);
				$(this).delay(out_delay).animate({marginTop:$(document).scrollTop() + $(window).height()+300},random_from_to(300, 800),function(){
					destroy_count++;
					if(destroy_count == total_count)
					{
						//scroll to the top
						$(window).scrollTop(0);
						//move nav to top
						$('#nav').css('top',0);
						$('.nav_bg').css('top',0);
						scroll_active = {col_1: true,col_2: true,col_3: true};
						$('#content').html('');
						$("#wrapper").trigger('show_page_in');
						boo_news_loaded = false;
					}
				});
		});
	}
	
	function load_blog_entries(obj_target)
	{
		if(arr_blog_entries.length > 0)
		{
			$.logThis('load entries');
			//$.logThis(arr_blog_entries);
			var j = 1;
			var img_count = 0;
			$.each(arr_blog_entries,function(i,item){
				if(j > 3)
				{
					j = 1;
				}
				var dateobj = item.getPublished().getValue().date;
				var curr_date = dateobj.getDate();
				var sup = 'th';
				if (curr_date == 1 || curr_date == 21 || curr_date ==31)
				   {
				   sup = "st";
				   }
				else if (curr_date == 2 || curr_date == 22)
				   {
				   sup = "nd";
				   }
				else if (curr_date == 3 || curr_date == 23)
				   {
				   sup = "rd";
				   }
				var curr_month = dateobj.getMonth();
				var curr_year = dateobj.getFullYear();
				var str_date = m_names[curr_month] + ' ' + curr_date +sup+ ' ' + curr_year;
				var content = $(item.content.$t);
				
				var arr_tmp_id = item.getId().getValue().split('post-');
				var int_id = arr_tmp_id[1];
				var a_tag = $('<a/>').attr('href','#news-'+int_id);
				
				var marginRight = $('.col_3').css('margin-right');
				if(marginRight.search('%') != -1)
				{
					//calculate the spacing for silly chrome browser
					marginRight = $('.col_3').parent().width()/100 * parseInt(marginRight.replace('%',''));
					$.logThis('CHROME MAGRIN: ' + marginRight);
				}
				var blog_item = $('<div/>')
							.append(a_tag)
							.addClass('blog_item')
							.css('marginBottom',marginRight);
				if(arr_blog_entries.length > 1)
				{
					blog_item.css('visibility','hidden');
				}
				a_tag.append($('<h2/>').html(item.getTitle().getText()))
							.append($('<p/>').html('Date.<br/>'+str_date));
				
				//add an image if we can find one
				var item_img = content.find('img');
				$.logThis('IMAGE? ' + i + 'count'+item_img.length);
				$.logThis(content.html());
				if(item_img.width() > 1)
				{
					img_count++;
					var resize = calculate_slider_size(item_img.width(),item_img.height(),false,$('.col_3').width());
					var src = item_img.attr('src').replace('s400',resize);
					a_tag.prepend($('<img/>').attr('src',src));
				}
				
				if(obj_target)
				{
					obj_target.append(blog_item);
				}
				else
				{
					$('#col_'+j.toString()).append(blog_item);
				}
				j++;
			});
			
			//animate the items in on first load
			if(arr_blog_entries.length > 1)
			{
				$.logThis('START ANIM IN' + arr_blog_entries.length);
				var count = 1;
				$('.blog_item img').load(function(){
					$.logThis('IMAGE LOADED');
					if(count == img_count)
					{
						$.logThis('START ANIM IN');
						animate_gallery_in($('.blog_item'));
					}
					
					count++;
				});
			}
			
			
			//unset all loaded entries
			arr_blog_entries = new Array();
		}
	}
	
	/************** NEWS ENTRY ****************/
	
	function build_news_entry()
	{
		$('#wrapper').css('background','none');
		boo_news_entry_loaded = true;
		build_sub_nav('News','news',new Array({title: 'View all news',link:'news'}));
		
		
		//load entry
		if(!blogger_service)
		{
			boo_news_entry_loaded = false;
			return;
		}
		blogger_service.getBlogFeed(blog_feed+ '/'+arr_hash[1],function(blogFeedRoot){
			
			$('#content').css('margin-top',$(window).height());
			var item = blogFeedRoot.entry;
			var dateobj = new Date(item.published.$t.substr(0,10).replace(/-/g,'/'));
			//var dateobj = new Date(item.published.$t);
			var curr_date = dateobj.getDate();
			var sup = 'th';
			if (curr_date == 1 || curr_date == 21 || curr_date ==31)
			{
				sup = "st";
			}
			else if (curr_date == 2 || curr_date == 22)
			{
				sup = "nd";
			}
			else if (curr_date == 3 || curr_date == 23)
			{
					sup = "rd";
			}
			var curr_month = dateobj.getMonth();
			var curr_year = dateobj.getFullYear();
			var str_date = m_names[curr_month] + ' ' + curr_date +sup+ ' ' + curr_year;
			var date = $('<p>Date.<br/>'+str_date+'</p>');
				
			var resize = Math.round(610 * $('#nav').width() / 940).toString();
			var entry_content = $('<p>'+item.content.$t+'</p>');
			var img_url = '';
			entry_content.find('img').each(function(){
					if($(this).width() > 1)
					{
						img_url = $(this).attr('src').replace('/s400/','/s200/');
						//disable image link
						$(this).parent('a').replaceWith($(this));
						$(this).attr('style','').width('auto').height('auto').css('margin','');
						$(this).attr('src',$(this).attr('src').replace('/s400/','/s'+resize+'/'));
					}
				});
				
			var blog_info = $('<div/>').addClass('blog_info col_4').append(date).append(share.clone());
				
			$('<article/>').addClass('entry_wrapper')
								.append($('<h2/>').html(item.title.$t))
								.append($('<div/>').addClass('blog_entry col_4').append(entry_content))
								.append(blog_info)
								.appendTo('#content');
			
			
			
			//twitter and facebook
			
			var str_current_link = 'http://' + window.location.hostname + '/news-'+arr_hash[1];
			var facebook_link = add_facebook_share(str_current_link,item.title.$t,item.content.$t,'blog',img_url);
			blog_info.find('.facebook').attr('href',facebook_link);
			blog_info.find('.twitter').attr('href',blog_info.find('.twitter').attr('href') + str_current_link);
				
				
			//animate everything in
			$('#content').animate({marginTop:0},300);
		},handle_blog_error);
		
			
			
	}
	
	function add_facebook_share(url, title, summary, type, image)
	{
		//type - audio, image, video, news, blog, and mult.
		
		//remove all existing ones
		$('head').find('meta[property^="og:"]').remove();
		$('head').find('meta[name="medium"]').remove();
		
		//add appropriate meta tags
		$('<meta name="medium" content="'+type+'" />').appendTo('head');
		$('<meta property="og:title" content="'+title+'" />').appendTo('head');
		$('<meta property="og:description" content="'+summary.substr(0,30)+'..." /> ').appendTo('head');
		$('<meta property="og:image" content="'+image+'" />').appendTo('head');
		/*
		//video
		<meta property="og:video" content="http://www.example.com/player.swf?video_id=123456789"/> 
		<meta name="og:video:height" content="200" /> 
		<meta name="og:video:width" content="300" />
		<meta name="og:video:type" content="application/x-shockwave-flash" />
		*/
		var link = 'http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(title);
		return link;
	}
	
	function destroy_news_entry()
	{
		$.logThis('destroy_news_entry');
		boo_news_entry_loaded = false;
		destroy_sub_nav();
		$('#content').animate({marginTop:$(window).height()},300,function(){
			$('#content').html('').css('margin-top',0);
			$("#wrapper").trigger('show_page_in');
		});
	}
	
	
	/************** INFO ****************/
	
	function build_info() {
		boo_info_loaded = true;
		
		$('#content').addClass('clearfix');
		$('#content').css('margin-top',$(window).height());
		$('#content').height('');
		$('.img_wrap').remove();
		//add fixed content
		
		//add logo
		var logo = new Image();
		logo.src = 'css/images/logo.gif';
		logo.alt = 'Josh Cole Logo';
		logo.width = 165;
		logo.height = 112;
		
		var info_content = $('<p>Josh is represented as a Photographer by Wyatt-Clarke and Jones:</p>'
				+'<p><a href="http://www.wyattclarkejones.com" target="_blank">www.wyattclarkejones.com</a>'
				+'<br/>Email.'
				+'<br/><a href="mailto:james@wyattclarkejones.com">james@wyattclarkejones.com</a>'
				+'<br/>Phone.'
				+'<br/>+44 20 7580 7570'
				+'</p><p>Josh is represented as a Director in the UK, LA and New York by Hungryman:'
				+'</p>'
				+'<p><a href="http://www.hungryman.com" target="_blank">www.hungryman.com</a>'
				+'<br/>Email.'
				+'<br/><a href="mailto:james@hungryman.com">james@hungryman.com</a>'
				+'<br/>Phone.'
				+'<br/>+44 20 7239 4550'
				+'</p>'
		);
		var info_side_content = 'Phone.<br/>+44 (0) 7834 041 419<br/>Email.<br/><a href="mailto:josh@joshcole.co.uk">josh@joshcole.co.uk</a>'
			+ '<br /><br />Social.<br/><a href="http://www.facebook.com/profile.php?id=667116453" target="_blank">Facebook</a>'
			+ '<br /><a href="https://twitter.com/#!/joshcole49" target="_blank">Twitter</a>'
			;
		$('<article/>').addClass('entry_wrapper clearfix infoline')
			.append($('<h2/>').html('Contact'))
			.append($('<div/>').addClass('blog_entry col_4').append(info_content))
			.append($('<div/>').addClass('blog_info col_4').html(info_side_content))
			.append($(logo).addClass('logo'))
			.prependTo('#content');
			
		//ad links
		var info_links = $('#content').after($('<article/>').addClass('entry_wrapper clearfix info_links'));
		$(".info_links").bind('gallery_is_in',function(e){
			var links = new Array( $('<h3/>').html('Web Design.'),
					$('<a/>').attr('href','http://www.studio-output.com').html('Studio Output'),
					$('<h3/>').html('Sponsor.'),
					$('<a/>').attr('href','http://www.innovaart.com').html('Innova Art Paper'),
					$('<h3/>').html('Art and Photo.'),
					$('<a/>').attr('href','http://www.heavyartillerycrew.com').html('Aroe'),
					$('<a/>').attr('href','http://www.favelapainting.com').html('Favela Painting'),
					$('<a/>').attr('href','http://www.markwardstudio.com').html('Mark Ward'),
					$('<a/>').attr('href','http://www.fakso.com').html('Fakso'),
					$('<a/>').attr('href','http://artofdavidwalker.com').html('David Walker'),
					$('<a/>').attr('href','http://ryca.net').html('Ryka'),
					$('<a/>').attr('href','http://www.matt-small.com').html('Matt Small'),
					$('<h3/>').html('Music.'),
					$('<a/>').attr('href','http://www.killakela.com').html('Killa Kela'),
					$('<a/>').attr('href','hhttp://www.docbrown.co.uk/').html('Doc Brown'),
					$('<a/>').attr('href','http://coderedagency.com/').html('Code Red (agency)'),
					$('<a/>').attr('href','http://www.wix.com/stigofthedumpuk/stig').html('Stig of the Dump'),
					$('<a/>').attr('href','http://www.skinnyman.co.uk/').html('Skinnyman'),
					$('<a/>').attr('href','http://www.rafikirecords.com').html('Rafiki Rwanda'),
					$('<a/>').attr('href','http://www.ministryofsound.com').html('Ministry'),
					$('<a/>').attr('href','http://officiallogic.com').html('Logic MC'),
					$('<a/>').attr('href','http://www.m0squito.com').html('J Majik and Wickaman'),
					$('<a/>').attr('href','http://www.myspace.com/cronxxx').html('Cronxxx Crew'),
					$('<a/>').attr('href','http://www.babyj.biz').html('Baby J'),
					$('<a/>').attr('href','http://www.thetrinityband.com').html('Trinity Band'),
					$('<a/>').attr('href','http://www.facebook.com/pages/Rodney-P/62946861750').html('Rodney P'),
					$('<h3/>').html('Dance.'),
					$('<a/>').attr('href','http://www.myspace.com/mousesweed').html('B-boy Mouse'),
					$('<a/>').attr('href','http://www.jonzi-d.co.uk/').html('Jonzi D'),
					$('<a/>').attr('href','http://www.flawlessofficial.com/').html('Flawless'),
					$('<a/>').attr('href','http://www.trinitywarriors.co.uk').html('Trinity Warriors'),
					$('<a/>').attr('href','http://www.facebook.com/profile.php?id=1337565243').html('Jed Lawrence/ Ubuntu (Cape Town)'),
					$('<a/>').attr('href','http://www.facebook.com/profile.php?id=100001677493561').html('Encore Crew (Durban)'),
					$('<a/>').attr('href','http://gillerbattlecrew.blogspot.com/').html('Giller Battle Crew (Malaysia)'),
					$('<h3/>').html('Social Projects.'),
					$('<a/>').attr('href','http://www.providenceproject.org/').html('Providence Drug Rehab'),
					$('<a/>').attr('href','http://www.careinternational.org.uk/').html('Care'),
					$('<a/>').attr('href','http://www.kidsco.org.uk/').html('Kids Company'),
					$('<a/>').attr('href','http://www.thecalmzone.net/').html('CALM'),
					$('<a/>').attr('href','http://www.uservoice.org/').html('User Voice/ Mark Johnson'),
					$('<a/>').attr('href','http://www.nikefoundation.org/').html('Nike Foundation'),
					$('<a/>').attr('href','http://www.girleffect.org/').html('Girl Effect'),
					$('<h3/>').html('Stylists.'),
					$('<a/>').attr('href','http://yasmineakkaz.com/').html('Yasmine Akkaz'),
					$('<a/>').attr('href','http://robynknight.co.uk/').html('Robyn Knight'),
					$('<h3/>').html('Production.'),
					$('<a/>').attr('href','http://www.shootlogistics.com/').html('Shoot Logistics'),
					$('<a/>').attr('href','http://www.marksummers.com/').html('Mark Summers (casting)'),
					$('<a/>').attr('href','http://www.locateproductions.com/').html('Locate Productions'),
					$('<a/>').attr('href','http://www.steel.co.za/').html('Steel Productions (Cape Town)'),
					$('<a/>').attr('href','http://www.thedairystudio.com/').html('The Dairy Studio (Shanghai)')
			);
			$(".info_links").append($('<div/>').addClass('infoline_top')
										.append($('<h2/>').html('Friends of Josh'))
								);
			$.each(links,function(i,item){
				item.attr('target','_blank').appendTo('.infoline_top');
			});
		});
		
		//build gallery
		$('<article/>').addClass('entry_wrapper clearfix')
					.append($('<h2/>').addClass('info_subtitle').html('About Josh'))
					.appendTo('#content');
		
		//animate everything in
		build_sub_nav('Info','info');
		//build_gallery(4,arr_info,false,false,false);
		
		$('#content').animate({marginTop:0},500,function(){
			build_gallery(4,arr_info,false,false,false,false,true);
		});
	}
	
	function destroy_info()
	{
		$('#content').removeClass('clearfix');
		boo_info_loaded = false;
		destroy_sub_nav();
		$('#content').animate({marginTop:$(window).height()},500,function(){
			$('#content').html('').css('marginTop',0);
			$(".info_links").remove();
			$("#wrapper").trigger('show_page_in');
		});
	}

	/************** ALL ****************/
	function build_all(boo_preview) {
		if(boo_preview)
		{
			
		}
		else
		{
			boo_all_loaded = true;
			build_sub_nav('All','all');
			var pag = 40;
			build_gallery(6,all_photos,'items',false,true,pag);
		}
	}
	function destroy_all() {
		boo_all_loaded = false;
		destroy_sub_nav(200);
		destroy_gallery(all_photos);
	}

	
/** HELPER FUNCTIONS **/
	
	function random_from_to(from, to) {
		return Math.floor(Math.random() * (to - from + 1) + from);
	}
	function makeid()
	{
	    var text = "";
	    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

	    for( var i=0; i < 5; i++ )
	        text += possible.charAt(Math.floor(Math.random() * possible.length));

	    return text;
	}
	function isScrolledIntoView(elem)
	{
	    var docViewTop = $(window).scrollTop();
	    var docViewBottom = docViewTop + $(window).height();

	    var elemTop = $(elem).offset().top;
	    var elemBottom = elemTop + $(elem).height();

	    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
	}


});



function set_current_image(int_active_image)
{
	if($('.activePage').index() != parseInt(int_active_image))
	{
		$('#slider').anythingSlider(parseInt(int_active_image)+1);
	}
}

function get_current_image()
{
	return $('.activePage').index();
}

function calculate_slider_size(img_width,img_height,boo_return_both,set_width,set_height)
{
	var aspect_ratio = img_width/img_height;
	var screen_height = (checker.iphone || checker.ipad) ? window.innerHeight : $(window).height();
	var window_height = screen_height - $('#nav').height() - screen_height/100*5;
	var window_width = $(window).width() - $(window).width()/100*10;
	//$.logThis('calculate_slider_size - set_height:' + set_height + ' width: ' + set_width);
	if(set_width)
	{
		window_width = set_width;
		if(set_height)
		{
			window_height = set_height;
		}
		else
		{
			window_height = 0;
		}
	}
	
	var new_width;
	var new_height;
	if(aspect_ratio > 1)
	{
		//landscape
		new_width = window_width;
		new_height = new_width/aspect_ratio;
		if(window_height && new_height > window_height)
		{
			new_height = window_height;
			new_width = aspect_ratio * new_height;
//			$.logThis(new_width+'x'+new_height);
		}
	}
	else
	{
		//portrait
		if(window_height > 0)
		{
			new_height = window_height;
			new_width = aspect_ratio * new_height;
		}
		else
		{
			new_width = set_width;
			new_height = new_width/aspect_ratio;
		}
		
		if(new_width > window_width)
		{
			new_width = window_width;
			new_height = new_width/aspect_ratio;
		}
	}
	
	if(boo_return_both)
	{
		return {width:Math.round(new_width),height:Math.round(new_height)};
	}
	else
	{
		resize_size = new_width > new_height ? new_width : new_height;
		if(Math.round(resize_size) > 2000)
		{
			resize_size = 2000;
		}
		//$.logThis('calculate_slider_size - resize_size:' + resize_size);
		return 's'+Math.round(resize_size).toString();
	}
}


var beforeload = (new Date()).getTime();
$.logThis = function( text ){
if( (window['console'] !== undefined) ){
	 var afterload = (new Date()).getTime();
     // now use the beforeload and afterload to calculate the seconds
     var secondes = (afterload-beforeload)/1000;
     //console.log(secondes);
   // console.log(text);
	}
};




